Looping an object to go back and forth between points

I’m trying to get an object to move back and forth between two points. I’ve set variables for the Origin and Destination coordinates, but only the Destination movement works. As soon as it gets there, it doesn’t turn back.

This is my event:

How can I loop it so that goes from Origin to Destination back to Origin, and so on?

I know the variables work, because if I only use one of those, the object travels from it’s current position to the variable coordinates.

This may just be an example of a common issue in GDevelop where an object may not perfectly fall on the position you are testing for if it is being moved by applying forces. In this case, your sub-event specifies that the position must = the destination positions, whereas you might be better off using > or < to check for a range around that position.

This is why back and forth movement is often done via collision checks with marker objects set at the two positions, as collisions test a range of values around a position.

You could also use the “Lerp” expression (linear interpolation) for movement between two points. Unfortunately the description of the function doesn’t tell very much. It takes three arguments:

  1. Start point
  2. End point
  3. Percentage between the two points (0.0 - 1.0 where 0.5 is right in the middle between the two points)
    Should be easier to calculate than using forces.

Thanks for the suggestion, which event should I be using for this? I can’t find any movement/position conditions that take those three arguments

It would be an action, but anyway it’s not an action, “lerp” is an expression that you have to use in the action to set position, it works this way:
“lerp(A, B, X)” returns a value between A and B in function of X, if X = 0 it returns A, if X = 1 returns B, if 0 < X < 1 it will return a value between A and B. For example for A = 1, B = 2 and X = 0.5 returns 1.5, and for X = 0.8 returns 1.8.
I guess you can use X < 0 or X > 1 to get values out of the range A-B. For example for A = 1, B = 2 and X = 3, it would return 4. If the lerp function doesn’t accept such values (X < 0 or X > 1) you can use your own function: “A + X*(B - A)”.

I have an example here using the lerp function to move back and forth between two points:
BackAndForth.gdg (15.5 KB)
Hope it helps :slight_smile:

Thanks for the example! However, I tried to open it in GDevelop 4 (the latest non-beta v5 version), and got a warning that the example was created with a newer version. I opened up the events and it was blank.
I then tried to open it in GDevelop 5, but it only allows you to open JSON files - would you be able to send is as a JSON instead? (Assuming you’re using v5)

Sorry, I was using an unstable build version, I’ve fixed it in the previous post :slight_smile: