Unity LookAt 2d Equivalent

2019-05-23 01:50发布

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.

2条回答
爷的心禁止访问
2楼-- · 2019-05-23 02:25

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));
查看更多
混吃等死
3楼-- · 2019-05-23 02:34

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;
}
查看更多
登录 后发表回答