V
V
Void592021-11-03 14:33:22
C++ / C#
Void59, 2021-11-03 14:33:22

Why doesn't rotation work correctly in Unity?

Good afternoon!
I have such a problem: one of the enemies should always turn towards the player, but for some reason confuses the sides.
When the player is on the top right, the opponent looks up to the left, when the player is on the top left - right up, when the player is on the bottom - the same. However, when the player is directly above or below this opponent, the opponent is facing directly at the player.
Here is a piece of code with rotation:

void Hunter()
    {
        Vector2 difference = transform.position - player.transform.position;
        float rot = Mathf.Atan2(difference.x, difference.y) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, rot + offset_for_hunter);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Crebor, 2021-11-03
@Crebor

var rotation = Quaternion.LookRotation (player.position - transform.position);
      rotation.x = 0.0f;//заморозка оси поворота x
      rotation.z = 0.0f;//заморозка оси поворота z
      transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * 5);

I did so. The turret rotated towards the player smoothly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question