[Daily of Unity3D] Mathf.Atan2 function research

I. Introduction

I recently used this function, so I will record the tips for using this function, so that I can review it later

Effect:
3d effect
Insert picture description here
2d effect
Insert picture description here

Second, the official API

Insert picture description here
This means that the tangent of the returned radian angle is y / x.
The return value is the angle between the x axis and the start zero and end 2D vector (x, y).
Note that this function returns the correct angle when x is 0, rather than throwing an exception divided by zero.

Next let's see how to use this function

3. Usage

Code:

using UnityEngine;

public class TestGetAnget : MonoBehaviour
{
    public Transform m_target1;
    public Transform m_target2;
    public Transform target;
    public Transform target1;

    void Update()
    {
        GetAnglev3();
        GetAngle(m_target1, m_target2);
    }

    void GetAnglev3()
    {
        Vector3 relative = target1.InverseTransformPoint(target.position);
        float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg;
        target1.Rotate(0, angle, 0);
    }

    void GetAngle(Transform target1,Transform target2)
    {
        Vector3 dir = target1.position - target2.position;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        m_target1.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }
}

3D demo At
Insert picture description here
this time, you can see our effect.
Insert picture description here
2D demo
Insert picture description here
Insert picture description here

Published 226 original articles · praised 509 · 530,000 views

Guess you like

Origin blog.csdn.net/q764424567/article/details/101270385