Top Down 2D Player Movement

Godot Version

4

Question

I’m trying to make the player node follow the mouse, and input be relational to the rotation of the node
Weirdly, I have to rotate the sprite within the node and add +90 in the script to the rotation for the inputs, not sure if there is a better way to re orientate the rigidBody2d so that inputs are relative to the node.

The code below works, but its VERY janky and seems to pull towards the right of the cursor somehow. I’m not sure why this happens though.

I feel like there should be a better way of doing what I’m trying to do. Does anyone maybe have feedback / know what is wrong with the following?

extends RigidBody2D

@export var speed = 10
func _ready():
	pass
func get_input():
	var input_direction = Input.get_vector("left", "right", "forward", "back") * speed
	look_at(get_global_mouse_position())
	apply_force(input_direction.rotated(rotation + 90.0))

func _physics_process(delta):
	get_input()

Its just a happy coincidence that your player moves towards the mouse at all lol.

The rotated method is in radians, not degres. So you are actually rotating it by 5156.62 degrees.

So you probably wants something like this.

apply_force(input_direction.rotated(rotation + deg_to_rad(90.0)))
1 Like

Since you use the looking_at function, your transform.x vector will point at your mouse.

Now you can use your input to move in the direction of your x basis.

First using your input vector you need to transform the input into the orientation of your rigidbody by calling:

Var transformed_input = transform.basis_xform(input_direction)
Apply_force(transformed_input)
1 Like

This explains the why I had to do the rotation, I do however find it weird that I cannot tell it to use the Y axis instead.

Here is the updated code for anyone else that might have problems:

func get_input():
	var input_direction = Input.get_vector("left", "right", "forward", "back") * speed
	look_at(get_global_mouse_position())
	rotation += deg_to_rad(90.0)
	apply_force(input_direction.rotated(rotation))

I undid the rotation I had on the sprite, and rather add another 90 degrees to the rotation before transforming the input direction.

It’s an arbitrary convention, the sprite default rotation seems trivial. It’s the same with 3D nodes where the -z axis is forward.

I think the drawback of not conforming is that you need to adjust for anything else that uses x as the main axis.

Maybe just rearrange the get_vector so that the x axis is your forward back , instead of left right.

I had not though of that, thanks. I’ll rearrange the get_vector to align to the x axis

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.