Topic was automatically imported from the old Question2Answer platform.
Asked By
Montasir Raihan
Actually, I’m making a 2d shooting game. And I can’t move my player as I want. I want my player rotate when I press the left and right arrow button and move forward and backward when I press the up and down arrow button. The direction also changes when I rotate my player. Here are the necessary codes.
func _physics_process(delta):
vel = Vector2()
var angle = PI/20
if Input.is_action_pressed(“Up”):
vel.y -= 1
if Input.is_action_pressed(“Down”):
vel.y += 1
if Input.is_action_pressed(“Left”):
rotate(angle)
if Input.is_action_pressed(“Right”):
rotate(-angle)
vel = move_and_slide(vel * player_speed)
I’m using kinematic Body 2d as a root node of my player. So how to do this? Please help me.
First, please use the “Code Sample” button to format your code when you post here. It will make it much more readable.
A for your question, the Godot docs include examples of this exact movement scheme:
In short: you need to rotate your velocity to move in the direction you’re facing. Note that the positive x axis is forward, as that represents 0 rotation.
Alternatively, you can use the transform to simplify things even more, as that represents the body’s rotation:
func _physics_process(delta):
vel = Vector2()
if Input.is_action_pressed("Up"):
vel += transform.x
if Input.is_action_pressed("Down"):
vel -= transform.x
if Input.is_action_pressed("Left"):
rotate(angle)
if Input.is_action_pressed("Right"):
rotate(-angle)
vel = move_and_slide(vel * player_speed)