2D sprite rotation in 3d world

Godot Version



I have a player that consists of a sprite of the player himself and his gun. I want to make his gun look at the mouse. To do this, I first find the mouse position in the 3d world using this code:

func get_mouse_position_3d():
var camera = get_viewport().get_camera_3d()
var position2D = get_viewport().get_mouse_position()
var dropPlane = Plane(Vector3(0, 0, 10), 0)
var position3D = dropPlane.intersects_ray(camera.project_ray_origin(position2D),camera.project_ray_normal(position2D))
return position3D

After that, if I were making a 2d game, I would use the look_at() function, but it doesn’t work correctly with 2d sprites in the 3d world.
How do I solve this problem?

You could flatten the positions along which axis you like, then use a 2D angle calculation like atan2

# swap z/x for everything but diff if you use a +Z forward.
func point_to_mouse() -> void:
    var mouse_pos3 := get_mouse_position_3d()
    var mouse_pos2 := Vector2(mouse_pos3.z, mouse_pos3.y)
    var pos2 := Vector2(position.z, position.y)

    var diff := mouse_pos2 - pos2
    var angle := atan2(diff.y, diff.x) 
    rotation.x = angle
1 Like

Thanks, everything worked out