Unity LookAt 2d 等效 [英] Unity LookAt 2d Equivalent
问题描述
我正在 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;
}
我尝试了两种选择,// 中的 1 和没有的.我试过 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.
推荐答案
我在我的游戏中进行这种类型的转换,使 2d 对象指向另一个对象.这与 x 轴成 0 度(向右)对齐.hitinfo 只是一个 RayCastHit2D,可以替换为您在代码中的目标位置.('Teh' 是故意的 :) )
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;
}
这篇关于Unity LookAt 2d 等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!