Unity LookAt 2d Equivalent

為{幸葍}努か 提交于 2019-12-06 08:54:25

I do this type of conversion in my games to make a 2d object point towards another object. This aligns by the x axis at 0 degrees (to the right). hitinfo is just a a RayCastHit2D and could be swapped out for your target's position you have in your code. ('Teh' is intentional :) )

currentProjectile.transform.rotation = Quaternion.Euler(0f, -90f, 0f) * Quaternion.AngleAxis(GetTehAngle(this.transform.position, hitinfo.point), Vector3.right);

private float GetTehAngle(Vector3 infrom, Vector3 into)
{
    Vector2 from = Vector2.right;
    Vector3 to = into - infrom;

    float ang = Vector2.Angle(from, to);
    Vector3 cross = Vector3.Cross(from, to);

    if (cross.z > 0)
        ang = 360 - ang;

    ang *= -1f;

    return ang;
}

There are explanations of a few different ways to do this in the dph blog.

I think the simplest version is:

transform.LookAt(Vector3.forward,Vector3.Cross(Vector3.forward,direction));

Or as you would want to use it in this instance:

transform.LookAt(Vector3.forward,Vector3.Cross(Vector3.forward,target.position - myTransform.position));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!