我在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);
}
答案 0 :(得分:1)
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
结果为from
到to
之间的中间角时。
因此,如果针需要以平稳恒定的速度移动,您应该这样做:
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%.
但是这需要from
和to
在lerp fase期间保持不变。
所以你需要做的是:
time = 0
,from = currentAngle
和to = maxAngle
;显然,在关键事件期间必须只执行一次。time = 0
,from = currentAngle
和to = 0
。也只做一次。好吗?
答案 1 :(得分:0)
您应该使用Time.deltaTime,而不是Time.time。这应该使它正确移动。
编辑:deltaTime不会单独解决问题。抱歉,我最初没有完全阅读您的代码。
为了平稳地移动针头,您需要知道针头当前的位置,需要去的位置,以及自上次移动以来经过的时间。
我们知道Time.deltaTime已经过了多长时间。但是你的代码目前没有考虑针的位置。 float angle = Mathf.LerpAngle(minAngle, maxAngle, Time.deltaTime);
将始终评估为大致相同的值,因此您的指针永远不会超出一点点。
你应该做的是从针的当前位置向maxAngle倾斜。
float angle = Mathf.LerpAngle(currentAngle, maxAngle, Time.deltaTime);