Answered by
10 years ago Edited 8 years ago
This code is definitely poorly designed.
Let's begin by tabbing your code properly
04 | button.Rotation = button.Rotation + 2 |
05 | if button.Rotation = = 20 then |
06 | button.Rotation = button.Rotation - 2 |
07 | if button.Rotation = = - 20 then |
08 | button.Rotation = button.Rotation + 2 |
Notice that the second if
for adding to Rotation
is inside the other one. That is almost certainly not what we want.
The wait(.1)
similarly doesn't belong, probably.
04 | button.Rotation = button.Rotation + 2 |
05 | if button.Rotation = = 20 then |
06 | button.Rotation = button.Rotation - 2 |
08 | if button.Rotation = = - 20 then |
09 | button.Rotation = button.Rotation + 2 |
We can also see that we're adding twice here instead of just once. That doesn't seem right, and it probably isn't, let's drop it.
04 | if button.Rotation = = 20 then |
05 | button.Rotation = button.Rotation - 2 |
07 | if button.Rotation = = - 20 then |
08 | button.Rotation = button.Rotation + 2 |
Now, here's a problem. Usually, Rotation
won't be either 20
or -20
. It can be something in between. Let's use a variable for the direction
instead, and just change direction
when we get to the ends:
05 | button.Rotation = button.Rotation + direction |
06 | if button.Rotation = = 20 then |
10 | if button.Rotation = - 20 then |
It would also probably be better to use >=
and <=
instead of ==
, just in case the numbers don't add up to exactly 20
(e.g., if you change the numbers, or things get more complicated)
03 | button.Rotation = button.Rotation + direction |
04 | if button.Rotation > = 20 then |
07 | if button.Rotation < = - 20 then |
We could make this a little cleaner and simpler by using button.Rotation
's magnitude (absolute value) instead of the separate numbers 20
and -20
:
2 | if math.abs(button.Rotation) > = 20 then |
3 | direction = -button.Rotation / 10 |
Or, instead of the linear jump back and forth, we could make things smooth by using a sin
(sine) function:
4 | time = time + wait( 0.2 ) |
5 | button.Rotation = 20 * math.sin( time ) |