Godot Version
4.3
Hello. I am really struggling to work out how to move my 2D player forward after the player has rotated. It’s Top Down 2D. Currently, after I rotate the player and move forward, the player just moves up (to the top of my screen) but I want the player to move forward relative to the direction they are facing after rotation. I am trying to keep my code simple without all the if statements. Is this possible to do in the format of code I have used?
extends CharacterBody2D
@export var vPlayerSpeed: int = 800
@export var vPlayerRotation: int = 5
func _physics_process(delta):
var vDirection = Input.get_vector("player1_move_left", "player1_move_right", "player1_move_up","player1_move_down") #("ui_left", "ui_right", "ui_up", "ui_down")
velocity = vDirection * vPlayerSpeed
var vRotation = Input.get_axis("player1_rotate_CW", "player1_rotate_CCW")
rotation_degrees -= vRotation * vPlayerRotation
move_and_slide()
Hey, I’m not explicitly using position. I am using the velocity and move_and_slide() which from what I understand uses vectors. But the vectors seem to be global and not local to the player.
1 Like
You can try to rotate the “vDirection” by the current rotation:
vDirection = vDirection.rotated(rotation)
Note that this might require a offset (like adding an extra 90 degree)
1 Like
Ok thanks I will give this a try
1 Like
No worries thanks for helping
I was able to achieve it with the following code;
extends CharacterBody2D
@export var speed = 400
@export var rotation_speed = 5
var rotation_direction = 0
func get_input():
var input_direction = Input.get_vector("player1_move_left", "player1_move_right", "player1_move_up", "player1_move_down")
velocity = input_direction * speed
rotation_direction = Input.get_axis("player1_rotate_CCW", "player1_rotate_CW")
func _physics_process(delta):
get_input()
rotation += rotation_direction * rotation_speed * delta
move_and_slide()
2 Likes