Y
Y
Yaroslav Kudrin2021-10-31 17:40:01
Mathematics
Yaroslav Kudrin, 2021-10-31 17:40:01

How to make an object rotate towards another object in Unity (2D)?

I have a 2D field in which the player and the enemy. We want the enemy to slowly turn towards the player (using Rigidbody2D.AddTorque if possible). How can this be implemented?

float rotation = ???;
rigidbody2d.AddTorque(rotation * Time.deltaTime * rotation_speed);


Edited: found this option, the enemy does something similar to turn the player, but somehow very strange
void LookAt(Vector3 point)
    {
        float scalar = point.x * transform.position.x + point.y * transform.position.y;
        float m1 = Mathf.Sqrt(point.x * point.x + point.y * point.y);
        float m2 = Mathf.Sqrt(transform.position.x * transform.position.x + transform.position.y * transform.position.y);
        transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, scalar / (m1 * m2) * 360);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yaroslav Kudrin, 2021-10-31
@Yarru

Found the answer on another site

transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, Mathf.Atan2(point.y - transform.position.y, point.x - transform.position.x) * Mathf.Rad2Deg - 90);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question