I’ve scripted a platform in a 2D space to loop back and forth between two points, A and B. To achieve this, I used the lerp() method. Here’s the code:
func moving_platform(delta_time):
match cube_state:
State.MOVING_UP:
if t < 1:
t += delta_time * speed
if t >= 1:
cube_state = State.MOVING_DOWN
State.MOVING_DOWN:
if t > 0:
t -= delta_time * speed
if t <= 0:
cube_state = State.MOVING_UP
cube.global_position = A.global_position.lerp(B.global_position, t)
The code above functions as intended. Before that, however, I had while instead of if and it didn’t work. The moment I run the game, the platform was already in point B, stuck. Here’s the previous code:
func moving_platform(delta_time):
match cube_state:
State.MOVING_UP:
while t < 1:
t += delta_time * speed
cube_state = State.MOVING_DOWN
State.MOVING_DOWN:
while t > 0:
t -= delta_time * speed
cube_state = State.MOVING_UP
cube.global_position = A.global_position.lerp(B.global_position, t)
I thought this would work but it didn’t and I’d love to know were I’m conceptually wrong in using the while loop here.
The if statements will drop through whereas the while statement will loop as long as the condition is true.
var x:int = 0
if x == 0: # this condition is true and 1 will be added to x and then the program drops through to the print
x += 1
print(x) # this will print 1
var x:int = 0
while x < 10: # this loop will keep adding 1 to x as long as the condition is true
x += 1
print(x) # this will print 10
If you’re calling this function from _process() understand that _process() is run automatically by engine, once per each rendered frame. The next frame won’t be rendered until all of the code in _process() is executed. So your whole while loop will do all its iterations during a single rendered frame, and the platform will immediately end up at the ending position.
In contrast, your first version moves the platform just a little bit each time it’s called, i.e. each rendered frame, and the final result will be gradual movement of the platform over time.
It would not. Physics process is also run once per frame, but once per physics frame instead of rendered frame. The issue is that you have a while loop inside a single process call. The game will not advance to the next frame until the while loop is finished.