我需要在Unity中使用c#将一个gameObject旋转到另一个gameObject,但我希望旋转只在z



我已经完成了这个程序,但是当我移动我的游戏对象(第二个)时,第一个游戏对象在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);
}

最简单的方法不是通过Quaternion,而是通过Vector3

很多人不知道的是:你不仅可以读取,还可以给例如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);
}

最新更新