统一如何访问脚本中的转换旋转

时间:2021-06-07 09:02:04

标签: c# unity3d

我正在制作一个弹跳和旋转盒子游戏。每次旋转分数都会增加。我写了一个关于它的代码,但不起作用。我搜索了互联网但找不到答案。

GameObject thePlayer = GameObject.Find("Player");
PlayerEverything player1 = thePlayer.GetComponent<PlayerEverything>();
if (!player1.isGrounded)
{
   if(thePlayer.transform.localRotation.z == 0) 
   {
       scorePoint++;
       scoreCombo++;
   }
   if(thePlayer.transform.localRotation.z == 90)
   {
       scorePoint++;
       scoreCombo++;
   }
   if(thePlayer.transform.localRotation.z == 180)
   {
       scorePoint++;
       scoreCombo++;
   }
   if(thePlayer.transform.localRotation.z == -180)
   {
       scorePoint++;
       scoreCombo++;
   }
   if(thePlayer.transform.localRotation.z == -90)
   {
       scorePoint++;
       scoreCombo++;
   }
   scoreCombo = scorePoint;
   score += scorePoint;
}

这是我编辑的代码

if (!player1.isGrounded)
{
    currentRotation += Vector3.SignedAngle( transform.parent.right,Vector3.up, transform.right);
    if (Mathf.Abs(currentRotation) > 90) 
    {
                
       scorePoint++;
       scoreCombo++;
    }
    Debug.Log("" + currentRotation);
    currentRotation = 0;
}    

GameImage

1 个答案:

答案 0 :(得分:3)

这里有多个问题!

首先从不使用 float 比较两个 == 值!由于浮点精度,这甚至可能失败,例如对于 5f * 0.2f / 10f == 1f .. 结果可能是 0.99999991.000000001

相反,您宁愿使用某个范围,例如

if(Mathf.Abs(a-b) <= someThreshold)

Unity 提供 Mathf.Approximately

<块引用>

比较两个浮点值,如果它们相似则返回真。

浮点不精确使得使用等号运算符比较浮点数不准确。例如, (1.0 == 10.0 / 10.0) 可能不会每次都返回 true。 Approximately() 比较两个浮点数,如果它们在彼此的小值 (Epsilon) 内,则返回 true。

所以使用

if(Mathf.Approximately(a-b))

基本上等于做

if(Mathf.Abs(a-b) <= Mathf.Epsilon)

Mathf.Epsilon 在哪里

<块引用>

浮点数可以具有的不为零的最小值。


那么Transform.rotationTransform.localRotation是一个Quaternion,它有四个组件xyz w。这些移动中的每一个都在 [-1; 1] 范围内移动。除非您确切地知道自己在做什么(您不知道;))从不直接读取或写入 Quaternion 的组件!

您的支票永远不会是true


相反,您应该使用向量并检查例如

// for storing the current rotation
private float currentRotation;
// for storing the last right direction
private Vector3 lastRight;

...    

if (!player1.isGrounded)
{
    // add the rotation delta since the last frame
    currentRotation += Vector3.SignedAngle(lastRight, transform.right, transform.forward);

    // if it exceeds +/- 90° 
    if(Mathf.Abs(currentRotation) > 90)
    {
        // get points
        scorePoint++;
        scoreCombo++;

        // and reset the rotation counter
        currentRotation = 0;
    }
}

// Update the last right direction with the current one
lastRight = transform.right;

Vector3.SignedAngle

相关问题