• 2D
  • How to get movement direction relative to sprite rotation?

I'm working on a top down shooter (like hotline miami). I have movement and sprite rotation. I'm trying to get the direction that the sprite is moving relative to it's rotation.

Here is a rough diagram.

So for example, if the sprite was facing right, and it was moving upwards somewhere in between the top two lines, I should be able to get that the sprite is moving "Left". I need this to work regardless of how the sprite is rotated.

The sprite faces the right by default, and I'm using look_at() to rotate it towards the mouse.

This is how I am getting input to move the player character.

	input_vector = Vector2.ZERO
	input_vector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
	input_vector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
	input_vector = input_vector.normalized()

Thanks in advance!

I'm not sure what you're asking. The movement and rotation are independent, and you can control both of them based on user input.

It almost sounds like you want to move the object in local space. Node2d has a move_local_x and move_local_y method.

6 days later

The issue that I'm having is I don't know how to get the players movement direction relative to the way their facing. Basically I want to be able to play the forward walking animation when they're walking towards the mouse, the backward walking animation when they're walking away from it, and the strafing animation when they're strafing. I've tried to calculate the angle of the input vector to the mouse position, but depending on the way player is rotated, this doesn't return the correct result.

@fire7side said: Well, maybe get the angle of the input vector https://godotengine.org/qa/71740/get-the-direction-of-a-vector2 and the angle of the sprite rotation from node2d Adjust the sprite rotation to 0 and then adjust the input vector angle the same amount, then compare it to the 4 directions angles

This worked for me. Thanks so much! In case anyone else runs into this. This is what I did.

func find_dir():	
	var angle = input_vector.rotated(0 - global_rotation).angle()
	if ((angle >= -PI / 4 && angle <= 0) || (angle >= 0 && angle <= PI / 4)):
		print("forward")
	elif((angle >= (3 * PI) / 4 && angle <= PI) || (angle <= -(3 * PI) / 4 && angle >= -PI)):
		print("backward")
	elif ((angle >= PI / 4 && angle <=(3 * PI) / 4)):
		print("right")
	elif ((angle <= -PI / 4 && angle >= -(3 * PI) / 4)):
		print("left")

Cool. Glad you got it working.