elijah
January 3, 2024, 9:17am
1
Godot Version
4.21
Question
I was following a tutorial on youtube and i ran into a problem my player will only move up and down but not left and right here is the code i used.
func player_movement(delta):
if Input.is_action_pressed("ui_right"):
velocity.x = Speed
velocity.y = 0
elif Input.is_action_pressed("ui_left"):
velocity.x = -Speed
velocity.y = 0
if Input.is_action_pressed("ui_down"):
velocity.y = Speed
velocity.x = 0
elif Input.is_action_pressed("ui_up"):
velocity.y = -Speed
velocity.x = 0
else:
velocity.x = 0
velocity.y = 0
move_and_slide()
if Input.is_action_pressed("ui_right"):
velocity.x = Speed
velocity.y = 0
elif Input.is_action_pressed("ui_left"):
velocity.x = -Speed
velocity.y = 0
elif Input.is_action_pressed("ui_down"):
velocity.y = Speed
velocity.x = 0
elif Input.is_action_pressed("ui_up"):
velocity.y = -Speed
velocity.x = 0
else:
velocity.x = 0
velocity.y = 0
move_and_slide()
1 Like
a0kami
January 3, 2024, 9:25am
3
The last else
negates the horizontal movement from the firsts if
and elif
.
You have to solutions to fix this:
Turn the second if
into an elif
:
if Input.is_action_pressed("ui_right"):
velocity.x = Speed
velocity.y = 0
elif Input.is_action_pressed("ui_left"):
velocity.x = -Speed
velocity.y = 0
elif Input.is_action_pressed("ui_down"):
velocity.y = Speed
velocity.x = 0
elif Input.is_action_pressed("ui_up"):
velocity.y = -Speed
velocity.x = 0
else:
velocity.x = 0
velocity.y = 0
move_and_slide()
or reset the velocity prior to the if
/elif
s and remove the last else
:
Edit : I read too fast, either way when you assign the vertical component you reset the horizontal speed because of x = 0
, you could set only the velocity component and combine horizontal and vertical to move in diagonals:
velocity = Vector2.ZERO
if Input.is_action_pressed("ui_right"):
velocity.x = Speed
elif Input.is_action_pressed("ui_left"):
velocity.x = -Speed
if Input.is_action_pressed("ui_down"):
velocity.y = Speed
elif Input.is_action_pressed("ui_up"):
velocity.y = -Speed
move_and_slide()
but notice that moving in diagonals will have increased velocity, you just have to normalize the vector before the move_and_slide()
to fix it.
velocity = velocity.normalized()
1 Like
system
Closed
February 2, 2024, 9:26am
4
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.