I have and issue to understand in chap 2 . mobile gameplay > lesson 3. horizontal Movement, the following line:
velocity.x= move_toward(velocity.x,0, speed)
in the function “_physics_process”:
func _physics_process(delta: float) -> void:
var direction = Input.get_axis("move_left", "move_right")
if direction:
velocity.x = direction * speed
else:
velocity.x= move_toward(velocity.x,0, speed)
move_and_slide()
if there is a move (right or left) is clear to me, but I do not understand why we do not use: velocity.x =0 directly if there is no move ( direction = 0 ) ?
Can you explain me:
why we use move_toward function as in this case we have no move (direction =0)
the velocity.x in the move_toward, is the previous vector2, so the previous x position ? I can understanf from.. to. However in this case I understand it as velocity.x (previous x position) x=0 new position = to. But it would mean that the player is always in movement and never stay at the same x position.
If a function has “move” in its name, it doesn’t necessarily mean it has to do anything with moving an object.
You can see the description of the function here:
What it does is it adjusts the value of the 1st argument towards the value of the 2nd argument, by the amount of the 3rd argument, while never surpassing the value of the 2nd argument.
So move_toward(1, 10, 3) will return 4, because 1+3. move_toward(50, 0, 10) will return 40, because 50-10. move_toward(0, 10, 20) will return 10, because 0+20 would surpass 10, which it can’t by the definition.
Etc…
In your example velocity.x = move_toward(velocity.x, 0, speed) you’re just moving the value from velocity.x towards value 0 by the amount of speed, and assigning the result back to the velocity.x
It’s just simple math, nothing to do with the actual movement of the character.
I read the documentation before asking, but in fact, what confused me was that the “small amount” was speed in both functions… so there is no acceleration or deacceleration in my code, because both have the same “step” which is “speed”.
to understand it, I just replaced speed in the move_toward function by “delta * speed”, to be able to understand that it was deacceleration until 0 (second argument).
that’s why, my first guess was just to set velocity.x = 0.
If in move_toward, the small amount is equal to the “same amount” of the velocity.x (which is in the “if direction:” condition), it is equal to velocity.x = 0, as there’s no deacceleration