当对象的 z 旋转超过限制时函数不触发
Function not firing when object's z rotation exceeds a limit
所以,我正在尝试制作一款大炮跟随鼠标的游戏。但是,我不希望它一直跟着它进入地下,所以我希望它在到达那里之前停下来。我尝试使用夹紧方法,但没有用。我尝试了一种不同的方法。这是我的代码:`
using UnityEngine;
public class CannonPoint : MonoBehaviour {
public GameObject cannon;
public float rotateSpeed = 5;
public float minAngle = -60;
public float maxAngle = 60;
void FixedUpdate(){
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}
void Update(){
if (transform.rotation.z > 71.759f) {
Debug.Log ("not working");
transform.rotation = Quaternion.Euler (transform.rotation.x, transform.rotation.y, 71.759f);
}
if (transform.rotation.z < -71.759f) {
Debug.Log ("not working");
transform.rotation = Quaternion.Euler (transform.rotation.x, transform.rotation.y, -71.759f);
}
}
}`
当我这样做时,函数没有触发。在更新中,检查器告诉我旋转实际上大于 71.759,但是 Debug.Log 没有触发 为什么会发生这种情况!我变得很困惑。谢谢!
(让你知道我的主要目标是防止大炮指向地下。)
当你在 Unity 中使用旋转时,在你完全理解它之前,刚开始的新手有点困惑。
请参阅当您从 transform.rotation
获取值时,它将 return 一个 Quaternion
[=34= 的对象] in.Unity Quaternion
的轴值从零(0)到一(1).
在您的情况下,您的条件不可能为真或 z 值不可能达到 71.759.
相反,我建议您使用 transform.eulerAngles.z
检查对象的旋转。
更新: 为您准备了一些代码,我已经为您准备了一些代码。
Vector3 v = Camera.main.ScreenToWorldPoint(Input.mousePosition);
v = v - t.position;
a = Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg - 90f;
Vector3 angles = t.eulerAngles;
angles.z = Mathf.Clamp(a, -70f, 70f);
t.eulerAngles = angles;
这也是您需要对其进行测试的全部内容。
有关瞄准鼠标指针位置的更多信息,请观看此视频 TOP DOWN SHOOTING in Unity
所以,我正在尝试制作一款大炮跟随鼠标的游戏。但是,我不希望它一直跟着它进入地下,所以我希望它在到达那里之前停下来。我尝试使用夹紧方法,但没有用。我尝试了一种不同的方法。这是我的代码:`
using UnityEngine;
public class CannonPoint : MonoBehaviour {
public GameObject cannon;
public float rotateSpeed = 5;
public float minAngle = -60;
public float maxAngle = 60;
void FixedUpdate(){
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}
void Update(){
if (transform.rotation.z > 71.759f) {
Debug.Log ("not working");
transform.rotation = Quaternion.Euler (transform.rotation.x, transform.rotation.y, 71.759f);
}
if (transform.rotation.z < -71.759f) {
Debug.Log ("not working");
transform.rotation = Quaternion.Euler (transform.rotation.x, transform.rotation.y, -71.759f);
}
}
}`
当我这样做时,函数没有触发。在更新中,检查器告诉我旋转实际上大于 71.759,但是 Debug.Log 没有触发 为什么会发生这种情况!我变得很困惑。谢谢!
(让你知道我的主要目标是防止大炮指向地下。)
当你在 Unity 中使用旋转时,在你完全理解它之前,刚开始的新手有点困惑。
请参阅当您从 transform.rotation
获取值时,它将 return 一个 Quaternion
[=34= 的对象] in.Unity Quaternion
的轴值从零(0)到一(1).
在您的情况下,您的条件不可能为真或 z 值不可能达到 71.759.
相反,我建议您使用 transform.eulerAngles.z
检查对象的旋转。
更新: 为您准备了一些代码,我已经为您准备了一些代码。
Vector3 v = Camera.main.ScreenToWorldPoint(Input.mousePosition);
v = v - t.position;
a = Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg - 90f;
Vector3 angles = t.eulerAngles;
angles.z = Mathf.Clamp(a, -70f, 70f);
t.eulerAngles = angles;
这也是您需要对其进行测试的全部内容。 有关瞄准鼠标指针位置的更多信息,请观看此视频 TOP DOWN SHOOTING in Unity