Unity LookAt 2d Equivalent

三世轮回 提交于 2020-01-02 09:29:09

问题


I'm creating a tank fighting 2D game top-down in Unity 3D in the 2D perspective active. My axises are X and Y (defaulted) and I'm trying to create a homing missile

My missile code is code is:

var enemyName   :String;    // which enemy does this shot seeks
private var target  :GameObject;
var speed       :float  = 100;
private var timeToTarget:float; 

function Start () {

    timeToTarget = Mathf.Abs(speed);

    if (timeToTarget<=0)
    {
        timeToTarget=150;
    }
    target = GameObject.Find(enemyName);
    Destroy(this.gameObject, timeToDie);
    myTransform = transform;
}

function Update () 
{

    rorate2target();
    follow();
}

function follow() //works fine
{
    transform.Translate(0,0,speed*Time.deltaTime);

}

and

function rorate2target()
{
    /*
        var rot : Quaternion = Quaternion.LookRotation( target.position - transform.position, -Vector3.forward );
        transform.rotation = rot;
    */
    var rot : Quaternion = Quaternion.LookRotation( target.position -    myTransform.position, -Vector3.forward );
    myTransform.rotation = rot; 
}

I tried both options, the 1 in the // and the one without. I tried LookAt that makes it rotate through the Z axis as well as stuff like

Quaternion rotation = Quaternion.LookRotation
            (Target.transform.position - transform.position, transform.TransformDirection(Vector3.up));
        transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);

None helped. What I want the missile to do is to "look" at the direction of its flight.


回答1:


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;
}



回答2:


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));


来源:https://stackoverflow.com/questions/22813825/unity-lookat-2d-equivalent

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