【问题标题】:I need to rotate a gameObject towards another gameobject in Unity with c#, but i want the rotation to be only in z我需要使用 c# 将一个游戏对象旋转到 Unity 中的另一个游戏对象,但我希望旋转仅在 z 中
【发布时间】:2021-12-13 23:59:29
【问题描述】:

我已经完成了这个程序,但是当我移动我的游戏对象(第二个)时,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.AngleAxis 试试这个 api 吗?

标签: c# unity3d rotation gameobject


【解决方案1】:

最简单的方法不是通过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);
}

【讨论】:

  • 谢谢,帮了大忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多