if not is_on_floor():
velocity += get_gravity() * delta
move_and_slide()
#moves left and right
func _input(event):
var direction = position.x
if event.is_action_pressed(“move_left”):
direction = -1
velocity.x = direction * SPEED
elif event.is_action_pressed(“move_right”):
direction = 1
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP
Question
I was wondering why when my character moves to the side, it will randomly stop in the middle of traveling for no reason.
I could be wrong but my first guess is that the line velocity.x = move_toward(velocity.x, 0, SPEED)
can’t be right. The function move_toward is used to move to a position, and you’re inputting velocity. This would cause it to keep slowing down, I think. Also you want a delta for that. I think you just don’t want move_toward at all in this case, just move_and_slide. You probably just don’t need the else case at all?
(I’m not sure how that is even working since you need to pass a Vector2 and you’re passing two floats, velocity.x and 0… unless Godot interprets two separate floats as a Vector2 when needed and I didn’t know about that. Are you sure the engine isn’t giving you an error there? (Check the debug console.)
move_toward takes three arguments, it “moves” the first toward the second by the third amount, using a negative value if necissary. It is equivalent to the following:
You are correct that using delta is encouraged and can fix this equation’s frame dependence. Though the math isn’t necessarily to move towards a position, instead it moves toward a value of any kind in any dimension. In this case, and in the current basic movement template the move_toward function is misused to reset the velocity.x to zero where = 0 would have sufficed.
There are Vector2, Vector3, and Vector4 variants of move_toward that take vectors as start and target parameters, which could move toward a position, though many use it to increase or decrease velocity towards a target speed.
oh yeah; you are using func _input instead of checking for movement inputs every frame under _physics_process. You should check out the basic movement template script for a CharacterBody2D.