我已經完成了這個程式,但是當我移動我的游戲物件(第二個)時,y 中第一個游戲物件的旋轉開始從 90 到 -90 隨機旋轉。
public GameObject target;
public float rotSpeed;
void Update(){
Vector3 dir = target.position - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotSpeed * Time.deltaTime);
}
uj5u.com熱心網友回復:
最簡單的方法不是通過Quaternion而是Vector3相反。
許多人不知道的是:您不僅可以讀取,還可以為 eg 分配一個值,transform.right該值將調整旋轉以便transform.right與給定方向匹配!
所以你可以做的是例如
public Transform target;
public float rotSpeed;
void Update()
{
// erase any position difference in the Z axis
// direction will be a flat vector in the global XY plane without depth information
Vector2 targetDirection = target.position - transform.position;
// Now use Lerp as you did
transform.right = Vector3.Lerp(transform.right, targetDirection, rotationSpeed * Time.deltaTime);
}
如果您需要在本地空間中使用它,因為例如您的物件在 Y 或 X 上具有默認旋轉,您可以使用
public Transform target;
public float rotSpeed;
void Update()
{
// Take the local offset
// erase any position difference in the Z axis of that one
// direction will be a vector in the LOCAL XY plane
Vector2 localTargetDirection = transform.InverseTransformDirection(target.position);
// after erasing the local Z delta convert it back to a global vector
var targetDirection = transform.TransformDirection(localTargetDirection);
// Now use Lerp as you did
transform.right = Vector3.Lerp(transform.right, targetDirection, rotationSpeed * Time.deltaTime);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344695.html
