@Bredemar said:
Hi @TwistedTwigleg. I checked the code, it really works. Thank you very much!!! But can you tell me what each line does?)
Sure, I can give a quick overview of what is going on.
Lines 1-6 are just defining the variables we'll need for the movement. The export keyword is used so you can input these values through the Godot editor.
Lines 8 and 9, the _ready function, simply get the global position of the object when it is initialized/ready, and stores it in the starting_position variable. We need to know the starting position so the two points we are using to linearly interpolate with.
In the _process function, lines 11+, we are actually handling the movement of the object. First, we use a condition to make sure that interpolation_value is less than one. This is because if interpolation_value is one or greater, than we have reached the target position and no longer need to attempt to move towards it.
After this condition, we add delta * speed to interpolation_value, which is line 13. delta is the length of time in seconds between each frame, and because games generally run at 60+ FPS, it is generally a small value. By multiplying it by speed, this means that for every second, one value of speed will be added to interpolation_value. This allows us to control how fast or slow interpolation_value increases.
Next, line 14 and 15, we use a condition to check and see if interpolation_value is more than one. If it is more than one, we set interpolation_value to one. We do this because we do not want to go past the target when interpolating.
Finally, line 16, we set the global position (global_transform.origin) of the object. We do this via the linear_interpolate function, which we call on starting_position. The linear interpolate function will mix the starting position and the final position together based on the passed-in weight, which in this case is interpolation_value.
When interpolation_value is 0 and used in this function, the object's position will be starting_position. When interpolation_value is 0.5, the object's position will be halfway between both starting_position and target_position, and finally, when interpolation_value is 1.0, the object's position will be at target_position.
So by using linear_interpolate, we can mix the two positions together, and because interpolation_value is increasing every time _process is called, this will slowly move the object from the starting_position to the target_position.
That's how the code works! I probably explained it poorly, but hopefully that helps a bit :smile: