2016-11-22 75 views
0

我有一些行星周围产生的宇宙飞船。我想让他们在这个星球上飞翔。旋转宇宙飞船,面对给定的方向矢量

我也希望他们旋转,他们正在飞行。因为此刻,组合屋只是其初始旋转方向。

我不知道,如果transform.RotateAround();就是拿这个问题的正确的。 Transform.Rotate()不起作用。

所以我的问题是,怎样才能让我的飞船飞周围的行星和旋转到它们飞行的方向?

这里是我到目前为止的代码:

Transform planet; // The planet to fly around 
float speed = 5;   // The movementSpeed 
Vector3 flyDirection; // The direction, it flies around 

void Start() 
{ 
    planet = GameObject.FindGameObjectWithTag("Planet").transform; // Get the transform of the planet 

    Vector3[] directions = { Vector3.left, Vector3.right, Vector3.up, Vector3.down }; // The possible directions to fly 
    flyDirection = directions[Random.Range(0, directions.Length)];   // Get a random fly direction 
} 

void Update() 
{ 
    transform.RotateAround(planet.position, flyDirection, speed * Time.deltaTime);   // Fly around the planet 
    transform.Rotate(..);  // Rotate the Object to the fly direction 
} 
+0

呃......澄清,是transform.RotateAround()'为你工作',或者是,只要你想要么不工作? – Serlite

+0

嘿,我真的不知道......对象正在飞来飞去,但他们并不绕着地球旋转。他们都在东部随机飞行... – Garzec

回答

1

移动飞船

此刻,你似乎没有被提供正确的参数Transform.RotateAround()。具体来说,第二个参数应该是执行旋转所围绕的轴线,在这种情况下,该轴线应该是垂直于期望的矢量的矢量以及船/行星之间的矢量,而不是flyDirection本身。我们可以得到这样的容易使用Vector3.Cross()

void Update() 
{ 
    // Calculating vector perpendicular to flyDirection and vector between ship/planet 
    Vector3 rotationAxis = Vector3.Cross(flyDirection, transform.position - planet.position); 
    transform.RotateAround(planet.position, rotationAxis, speed * Time.deltaTime); 

    // ... 
} 

旋转飞船

一个快捷方式来设置对象的旋转面对任意方向是将值赋给它transform.forward属性。你的情况,你可以简单地提供flyDirection作为新forward矢量使用方法:

void Update() 
{ 
    // Calculating vector perpendicular to flyDirection and vector between ship/planet 
    Vector3 rotationAxis = Vector3.Cross(flyDirection, transform.position - planet.position); 
    transform.RotateAround(planet.position, rotationAxis, speed * Time.deltaTime); 

    // Setting spacecraft to face flyDirection 
    transform.forward = flyDirection; 
} 

如果你需要为这个特定的四元数的值,或需要飞船的transform.up总是一个特定的方向指向(例如,普通到。地球表面),然后考虑使用Quaternion.LookRotation()来设置旋转。

希望这会有所帮助!如果您有任何问题,请告诉我。

+0

感谢您的帮助。我伤心这个代码没有工作。太空船开始卡在轴上。我做了一个截图:http://imgur.com/a/qZ54g现在他们不能再动弹了。 – Garzec

+0

@Garzec Hm,有趣。我的猜测是,如何定义可用的“方向”是一个问题 - 这四个方向与船舶停靠的轴线对齐(此时,船与行星之间的矢量基本相同作为'flyDirection',导致交叉产品失败)。你能提供一个关于船只如何行为的GIF,直到它们卡住了吗? – Serlite