Unity LookAt 2d等效 [英] Unity LookAt 2d Equivalent

查看:273
本文介绍了Unity LookAt 2d等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Unity 3D中自上而下地在2D透视图中创建一个坦克战斗2D游戏。
我的轴是X和Y(默认值),我正在尝试制造一种寻的导弹

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

我的导弹代码是:

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

}

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

我尝试了两个选项, // 和一个没有。
我尝试过LookAt使其通过Z轴
以及

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.

推荐答案

有一些解释。 dph博客的不同方法

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

这篇关于Unity LookAt 2d等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆