首页 > 解决方案 > Unity 中逼真的阀轮旋转

问题描述

我正在 Unity 中进行逼真的管道阀轮旋转。这是我已经拥有的:

 [SerializeField] private float cur_HP;
private const float max_HP = 100;
private Vector3 PrevmousePos;
private bool SpaceIsPressed;
// Start is called before the first frame update
void Start()
{
    cur_HP = max_HP;
}

// Update is called once per frame
void Update()
{
    SpaceIsPressed = Input.GetKey(KeyCode.Space);
    Wheel();


}

void Wheel()
{
    Vector3 mouseDelta = Input.mousePosition - PrevmousePos;

    if (mouseDelta.x > 0 && SpaceIsPressed)
    {
        float amount = 0.01f;
        cur_HP -= mouseDelta.x * amount;
    } else if(mouseDelta.x < 0 && SpaceIsPressed)
    {
        float amount = 0.01f;
        cur_HP += mouseDelta.x * amount;
    }
    if (cur_HP <= 0)
    {
        cur_HP = 0;
        Debug.Log("You have unlocked");
    }
    if (cur_HP > 100)
    {
        cur_HP = 100;
    }
    transform.localRotation = Quaternion.Euler(0, 0, (720 / max_HP * cur_HP));
    PrevmousePos = Input.mousePosition;
}

我现在想要什么。就像现实生活中的阀门管轮一样。如果你想松开它。你需要用很大的力才能向右旋转。然后越松开它就越容易旋转。如果你想收紧它,反之亦然。所以在我的帮助下,我的小脑袋想不出任何数学或代码。你们能给我提示或提示如何做吗?

编辑:这是关于我现在拥有的 gif,我正在使用鼠标右扫的空格键来旋转滚轮https://gyazo.com/004b2f8c4424476c796ae42ad28dacce

标签: c#unity3d

解决方案


所以你有cur_HPwhich 应该设置阀门旋转多少,它是用 设置的mouseDelta.x

您现在希望下一个修改 ( mouseDelta.x) 更小,更cur_HP接近max_HP

cur_HP += (mouseDelta.x * max_HP/cur_HP) * amount;

这将使车轮越接近终点,线性速度就越慢。

您可能需要调整该amount变量,因为当旋转 1 度时,车轮现在将旋转 100 倍。

确保在 cur_HP 为 0 时进行处理,因为除以零是非常非法的。


示例,相同的 X 运动,不同的松紧度:

紧密度 20%

  • cur_HP = 20
  • 最大生命值 = 100
  • mouseDelta.x = 1
  • 数量 = 0.1f

--> 新 cur_HP = 20.5

紧密度:60%

  • cur_HP = 60
  • 最大生命值 = 100
  • mouseDelta.x = 1
  • 数量 = 0.1f

--> 新 cur_HP = 60.16666


推荐阅读