我需要使用 c# 将游戏对象旋转到 Unity 中的另一个游戏对象,但我希望旋转仅在 z 方向

I need to rotate a gameObject towards another gameobject in Unity with c#, but i want the rotation to be only in 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

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

如果你在本地需要这个 space 因为例如您的对象在 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);
}