[英]I need to rotate a gameObject towards another gameobject in Unity with c#, but i want the rotation to be only in z
I have done this program but when i move my gameobject(the seccond one) the rotation of the first gameObject in y starts to go randomly from 90 to -90.我已经完成了这个程序,但是当我移动我的游戏对象(第二个)时,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);
}
The simplest way for this is not going through Quaternion
but Vector3
instead.最简单的方法不是通过
Quaternion
而是通过Vector3
。
What many people don't know is: You can not only read but also assign a value to eg transform.right
which will adjust the rotation in order to make the transform.right
match with the given direction!许多人不知道的是:您不仅可以读取,还可以为例如
transform.right
赋值,它会调整旋转以使transform.right
与给定的方向匹配!
So what you can do is eg所以你可以做的是例如
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);
}
If you need this in local space since eg your object has a default rotation on Y or X you can adjust this using如果您需要在本地空间中使用它,因为例如您的对象在 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.