为什么我的 Unity 旋转检查不起作用?

问题描述 投票:0回答:2

问题

我的代码旨在在生成时将摆动武器设置到扫掠边缘范围的一侧,每帧旋转它,然后检查它是否摆动得很远,如果摆动到很远,则摧毁它。生成和旋转工作正常,但无论我如何配置检查旋转量的 if 语句,它要么不起作用,要么立即销毁对象。

我已经尝试过的

我尝试了以下的每一种组合:

  • 取反扫描边缘变量
  • 翻转比较符号
  • 在开始时对设置旋转的变量求反
  • 改变摆动方向 任何其他故障排除方法或其他解决方案将不胜感激。作为参考,更新函数中的代码如下。

参考代码

if (delayTimer > 0 && !hasStarted) {  //Note: This if statement is necessary so that the code doesn't try to initialize until the variables are set
            if (weapon == null) {  // Note: Weapon is a variable used to hold the weapon data like damage and sweeping edge range
                Debug.Log("No weapon referenced.");
                return;
            }
            Debug.Log("Found weapon");
            transform.localScale = new Vector3(0.2f, weapon.attackRange + 0.5f, 1);
            transform.Rotate(Vector3.forward * -weapon.sweepingEdgeRange / 2);
            transform.Translate(0, transform.localScale.y / 2, 0);
            hasStarted = true; //Note: This prevents the initialization from running more than once
        }
        delayTimer++; //Note: Necessary for initialization
        transform.Translate(0, -transform.localScale.y / 2, 0);
        transform.Rotate(Vector3.forward * 0.5f);
        transform.Translate(0, transform.localScale.y / 2, 0);
        if (transform.rotation.z >= weapon.sweepingEdgeRange) {
            Debug.Log("Too far!");
            Destroy(gameObject);
        }

我还注意到 Rotate() 函数旋转输入数字的相反方向,但我尝试用否定来解释这一点,但它不起作用。 (请参阅我尝试过的部分)

c# unity-game-engine
2个回答
0
投票

您需要使用eulerAngles。固定代码:

if (transform.rotation.eulerAngles.z < weapon.sweepingEdgeRange) {
transform.Rotate(Vector3.forward * 0.5f);

0
投票

我认为问题在于最后一个 if 条件:

transform.rotation
是一个
Quaternion
, 这不能直接与(我认为)标量值进行比较
weapon.sweepingEdgeRange
。因此,您应该获取 绕 z 轴旋转的角度。

例如,您可以使用 transform.localEulerAngles, 这是

相对于父变换旋转的欧拉角旋转。

// We use 'z' component for rotation around z axis
float currentRotation = transform.localRotation.eulerAngles.z;

if (currentRotation < 0)
{
  currentRotation += 360;
}

if (currentRotation >= weapon.sweepingEdgeRange || 
  currentRotation <= -weapon.sweepingEdgeRange)
{
  Debug.Log("Too far!");
  Destroy(gameObject);
}
© www.soinside.com 2019 - 2024. All rights reserved.