【问题标题】:Smoothly Lerp object based on button press Unity基于按钮按下 Unity 平滑 Lerp 对象
【发布时间】:2014-01-28 16:38:10
【问题描述】:

我在 Unity 中创建了一个速度计,我希望我的速度箭头能够平滑地上升到基于凋零或没有按下按钮的最大角度。松开按钮后,我希望箭头回退到原来的旋转值。

但是,我在尝试解决如何使我的对象从其原始位置到新位置并再次返回时遇到问题。我明白了,所以当我按下按钮时,对象会跳到一个位置,但是,我需要它更平滑。有人可以查看我的代码并指出我需要做什么吗?

float maxAngle = 100.0f;
float maxVel = 200.0f;
Quaternion rot0;
public float rotateValue;

// Use this for initialization
void Start () 
{
    rot0 = transform.localRotation;
}

// Update is called once per frame
void Update ()
{
    if(Input.GetKey(KeyCode.Space))
    {
        SetNeedle(rotateValue);
    }
}

void SetNeedle(float vel)
{
    var newAngle = vel * maxAngle / maxVel;

    transform.localRotation = Quaternion.Euler(newAngle,0,0) * rot0;


    float angle = Mathf.LerpAngle(minAngle, maxAngle, Time.time);
    transform.eulerAngles = new Vector3(0, angle, 0);
}

【问题讨论】:

    标签: c# rotation unity3d


    【解决方案1】:

    来自documentation

    static float Lerp(float from, float to, float t);
    Interpolates between a and b by t. t is clamped between 0 and 1.
    

    这意味着t 从 0% 变为 100%。当t == 0.5f 时,结果将是fromto 之间的中间角。

    因此,如果需要以平稳且恒定的速度移动机针,您应该这样做:

    time += Time.deltaTime; // time is a private float defined out of this method
    if(time >= 1.5f) // in this example the needle takes 1.5 seconds to get to its maximum position.
        time = 1.5f // this is just to avoid time growing to infinity.
    float angle = Mathf.LerpAngle(from, to, time/1.5f); // time/1.5f will map the variation from 0% to 100%.
    

    但这需要fromto 在 lerp 期间保持不变。 所以你需要做的是:

    • 按空格键时,设置time = 0from = currentAngleto = maxAngle;显然,这只能在按键事件期间执行一次。
    • 释放空间时,设置time = 0from = currentAngleto = 0。也只能这样做一次。

    好吗?

    【讨论】:

    • 感谢您的解释,我阅读了无数示例,但使用旋转持续时间(在您的示例中为 1.5f)为我澄清了这一点!这比使用一些旋转速度更容易理解......
    • @Mentoliptus 谢谢 :)
    【解决方案2】:

    您应该使用 Time.deltaTime,而不是 Time.time。这应该使它正确移动。

    编辑:不过,deltaTime 并不能单独解决问题。抱歉,我一开始没有完全阅读您的代码。

    为了顺利移动指针,你需要知道指针当前在哪里,它需要去哪里,以及距离上次移动已经过去了多少时间。

    我们知道 Time.deltaTime 已经过去了多少时间。但是您的代码目前没有考虑针在哪里。 float angle = Mathf.LerpAngle(minAngle, maxAngle, Time.deltaTime); 将始终评估为大致相同的值,因此您的指针永远不会超过一点点。

    您应该做的是从针的当前位置向 maxAngle 倾斜。

    float angle = Mathf.LerpAngle(currentAngle, maxAngle, Time.deltaTime);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多