Rotating a 3D body to look at mouse cursor

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By nikifaets

Hi guys,

I am trying to implement a behavior similar to the look_at() function but with the body only rotating around the Y axis. I am casting a ray from the camera through the mouse cursor and I’m detecting its collision point with the world. I want my kinematic body to be facing this point when I click the mouse.

To do this, I’m calculating the angle between player.basis.z and the world cursor coordinates relative to the player translation and then rotating the body at that angle. It’s pretty much the following piece of code:

var player_z = player.get_global_transform().basis[2].normalized()
var direction = collider_pos - player.translation
direction.y = 0
var angle = player_z.angle_to(direction.normalized())
player.rotate_y(angle+PI)

Here is a top view of the situation: godot-question hosted at ImgBB — ImgBB

However, if I keep the mouse button pressed, it keeps rotating instead of stopping at the given angle. (The rotated z-vector of the basis and the direction should be parallel?).

Here is a gif of what happens: Peek-2020-02-08-12-41 hosted at ImgBB — ImgBB

I would love to hear any suggestions and tips on how to fix this!
Thank in advance!

P.S. I’m setting direction.y to 0 because for some reason the collision point’s y-coordinate is slightly above 0 (The y-coordinate of the ground is 0).