浪费了很多时间试图找出轮换方式,并花费了很多时间来寻找答案,但找不到任何适合我的问题的方法。我需要将整个gameObject旋转到特定方向,而不是沿y轴旋转:
1)在Quaternion.LookRotation或Atan2内部指定方向的同时,当前对象如何旋转。2,3)旋转方式的示例。红色ot简化了发生旋转的枢轴点
除了要旋转的gameObject转换和旋转gameObject的方向以外,没有太多代码要显示,因为没有太多代码。
按照要求
[System.Serializable]
public class ToRotate
{
//Object which will be rotated by the angle
public GameObject gameObject;
//Object last known position of this object. The object is rotated towards it's last global position
private Vector3 lastPosition;
//Initializes starting world position values to avoid a strange jump at the start.
public void Init()
{
if (gameObject == null)
return;
lastPosition = gameObject.transform.position;
}
//Method which updates the rotation
public void UpdateRotation()
{
//In order to avoid errors when object given is null.
if (gameObject == null)
return;
//If the objects didn't move last frame, no point in recalculating and having a direction of 0,0,0
if (lastPosition == gameObject.transform.position)
return;
//direction the rotation must face
Vector3 direction = (lastPosition - gameObject.transform.position).normalized;
/* Code that modifies the rotation angle is written here */
//y angle
float angle = Mathf.Rad2Deg * Mathf.Atan2(direction.x, direction.z);
Quaternion rotation = Quaternion.Euler(0, angle, 0);
gameObject.transform.rotation = rotation;
lastPosition = gameObject.transform.position;
}
}
由于您希望对象的局部向下指向一个计算出的方向,同时尽可能保持对象的局部权不变,因此我将使用Vector3.Cross
查找该对象的向下和右侧的叉积来确定对象的局部正向应该面对的方向,然后使用Quaternion.LookRotation获得相应的旋转:
//Method which updates the rotation
public void UpdateRotation()
{
//In order to avoid errors when object given is null.
if (gameObject == null)
return;
//If the objects didn't move last frame, no point in recalculating and having a direction of 0,0,0
if (lastPosition == transform.position)
return;
//direction object's local down should face
Vector3 downDir = (lastPosition - transform.position).normalized;
// direction object's local right should face
Vector3 rightDir = transform.right;
// direction object's local forward should face
Vector3 forwardDir = Vector3.Cross(downDir, rightDir);
transform.rotation = Quaternion.LookRotation(forwardDir, -downDir);
lastPosition = transform.position;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句