【问题标题】:Limit HingeJoint rotation between angles限制角度之间的铰链关节旋转
【发布时间】:2018-10-21 16:24:12
【问题描述】:

我的脚本运行得几乎完美,但我只需要钳制这个浮点数,我似乎不知道怎么做。

简化版...

public HingeJoint doorHinge;
public float rotatedoor = 0.0f;  // Limit this value, min 0 max 120

void Update () {

       float h = Input.GetAxis("Mouse X");
       rotatedoor = rotatedoor + h;


        JointSpring doorSpring = Door.spring;
        doorSpring.targetPosition = rotatedoor;
        Door.spring = doorSpring;
}

我尝试添加一个最小和最大浮点值,然后使用

rotatedoor = Mathf.Clamp(rotatedoor, minRot, maxRot);

但没有运气。

感谢任何帮助。

【问题讨论】:

  • 试试这个:Math.Max(0, Math.Min(120, rotatedoor))
  • 他正在使用 Unity3D 并尝试使用 Mathf.Clamp() 方法来强制执行限制。 @Chris,您在使用 Mathf.Clamp() 时会得到什么结果?这实际上应该是正确的方法,除非有其他因素影响rotatedoor 变量的值。
  • 它反而停在 33 处,然后再试一次后它上升了一点,但不会回落.. 不知道为什么。三元表达式起作用了。

标签: c# unity3d


【解决方案1】:

你得到了关于夹紧它的答案,但你真的不需要这样做。

您似乎想为HingeJoint 设置限制。这具有使用 JointLimits 结构执行此操作的内置属性,这就是您应该使用的。

如下所示:

public HingeJoint doorHinge;
public float rotatedoor = 0.0f;  // Limit this value, min 0 max 120

void Update()
{
    //Get the current the limit
    JointLimits limits = doorHinge.limits;

    //Set the limit to that copy 
    limits.min = 0;
    limits.max = 120;

    limits.bounciness = 0;
    limits.bounceMinVelocity = 0;

    //Apply the limit since it's a struct
    doorHinge.limits = limits;

    JointSpring doorSpring = doorHinge.spring;
    doorSpring.targetPosition = rotatedoor;
    doorHinge.spring = doorSpring;
}

【讨论】:

  • 我已经设置了限制。我应该解释说这是一个门系统,就像你在失忆症或恐惧层中发现的那样。门永远不会超过限制,但浮动的值会,从而使关闭门需要更长的时间(如果这有意义的话)。虽然上面的修复已经奏效,但我现在遇到了另一个问题。出于某种原因,第一次互动后,需要两次点击才能再次互动。
  • 您没有提到您已经在问题中设置了限制,但这就是如何做到的。假设您已经这样做了,但也必须限制 rotatedoor 变量,那么上面的答案是可以的。抱歉,我不明白您的第二个问题,也许您应该针对该问题创建新问题
【解决方案2】:

有很多简单的方法可以做到这一点,所以我将在下面列出我看到的那些。

rotatedoor = Math.Max( 0f, Math.Min( 120f, rotatedoor ) );

或者,您可以使用a ternary expression:

rotatedoor = (rotatedoor < 0f) ? 0f : (rotatedoor > 120f) ? 120f : value;

或者,您可以使用 Unity3D 的Mathf.clamp()

rotatedoor = Mathf.clamp( rotatedoor, 0.0f, 120f );

可能还有其他方法可以做到这一点。我很想知道是否存在更有效的方法,因为所有这些技术都需要在update 逻辑中操作,这本身并不是最有效的方法。希望这会有所帮助!

【讨论】:

  • 值得注意的是,在克里斯提到这不起作用之前,我在这个答案中包含了 clamp 函数。一旦提供更多信息,很高兴更新答案。
  • 我不确定为什么 Mathf.Clamp 不起作用,在询问之前我对其进行了研究,这似乎是最好的方法。三元表达式已按预期工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多