Facing the player character towards the mouse cursor

Godot Version

4.6.1

Question

Hello there!

I tried to implement turning the player character towards the mouse using:

extends CharacterBody2D

@export var speed = 400

func get_input():
	look_at(get_global_mouse_position())
	velocity = transform.x * Input.get_axis("down", "up") * speed

func _physics_process(delta):
	get_input()
	move_and_slide()

I’ve found this in the Godot manual.
The problem is that I use a top-down placeholder sprite and my character starts to follow the mouse sideways, with his right shoulder in front as if it was the front of his body. I tried to rotate the character manually to 90 degrees, but it did not solve the situation. Any tips? Thanks!

That’s fully expected if you check the description of the Node2D::look_at() function

Rotates the node so that its local +X axis points towards the point, which is expected to use global coordinates.

If you don’t want that, you can offset the resulting rotation. E.g. this will rotate the node 90 degrees more, so that its top will face the mouse position.

	look_at(get_global_mouse_position())
	rotate(TAU / 4) ## this is 360 / 4 = 90 degrees

Thanks. This solved it!

1 Like