How to rotate an object towards another object

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

I want an object, an eye, in this case, to smoothly rotate to look at the player. How would I achieve this? A full code example would be greatly appreciated!

:bust_in_silhouette: Reply From: OgGhostJelly

you can use move_toward to smoothly rotate to the player.

func _process(delta: float) -> void:
    # gets the angle we want to face
    angle_to_player = global_position.direction_to(player_position).angle()

    # slowly changes the rotation to face the angle
	rotation = move_toward(rotation, angle_to_player, delta)
 var angle_to_player

 func _physics_process(delta):
    angle_to_player = global_position.direction_to(player_body.position).angle()
	
    $EyeAxis.rotation = move_toward($EyeAxis.rotation, angle_to_player, delta)

With the following code I get errors:
“Cannot find property “angle” on base “Vector3”.”
“Function “angle()” not found in base Vector3.”
Any clue what I’m doing wrong?

Scorch | 2023-05-03 14:55

Vector3 doesn’t have an angle method unlike Vector2, you can do this instead

angle_to_player = global_position.angle_to(player_body.position)

tell me if that works, I haven’t tested it myself yet :slight_smile:

OgGhostJelly | 2023-05-05 05:15

:bust_in_silhouette: Reply From: TRAILtheGREAT

A simpler method than the other answer would be to work directly on the basis:

func _process(delta):
    var target_vector = global_position.direction_to(player_position)
    var target _basis= Basis.looking_at(target_vector)
    basis = basis.slerp(target_basis, 0.5)

This works perfectly! Thanks

Scorch | 2023-05-03 19:10

1 Like

This should be equivalent in C#

var targetVector = GlobalPosition.DirectionTo(playerPosition);

// Throws exception if targetVector == 0
if (targetVector == Vector3.Zero) 
{
    return;
}

var target = Basis.LookingAt(targetVector);
Basis = Basis.Slerp(target, 0.1f);