我如何创造一个弹跳球,以反弹到相同的高度,我可以让它更快或更慢?一个人告诉我使用:
heightVector * |sin(time * speed)|
但我不知道在哪里插入它。我对这些事情真的很不错。救命!
你的公式是正确的。
heightVector
是你球的最大高度。例如,如果它是(0,10)
,那么这意味着你的球将高达10米。
time
只是一个计时器。 speed
是你的速度。
但是,我建议将速度乘以Time.deltaTime
以使反弹帧速率独立。
我们开始编写代码。
heightVector
和speed
没有复杂性。只需创建两个公共字段就可以了!
class Bouncer : MonoBehaviour
{
public float Speed = 10;
public Vector2 HeightVector = new Vector2(0,10);
}
要创建计时器,您需要一个float
变量。然后你需要在每次Time.deltaTime
调用时添加Update
。
class Bouncer : MonoBehaviour
{
public float Speed = 10;
public Vector2 HeightVector = new Vector2(0,10);
float timer;
void Update()
{
timer += Time.deltaTime;
}
}
恭喜!你现在有你的计时器!
现在你真的快要结束了。您只需计算球的当前位置并将其应用于其变换。
class Bouncer : MonoBehaviour
{
public float Speed = 10;
public Vector3 HeightVector = new Vector3(0,10);
float timer;
void Update()
{
timer += Time.deltaTime;
Vector3 currentPosition = HeightVector * Mathf.Abs(timer * Speed * Time.deltaTime);
transform.position = currentPosition;
}
}
现在你需要将Bouncer脚本附加到你的球上,你的球应该开始弹跳!
编辑:如果您希望球保持其原始位置并从那里反弹,您需要保持原始位置并将计算出的位置附加到它:
class Bouncer : MonoBehaviour
{
public float Speed = 10;
public Vector3 HeightVector = new Vector3(0,10);
Vector3 originalPosition;
float timer;
void Start()
{
originalPosition = transform.position;
}
void Update()
{
timer += Time.deltaTime;
Vector3 currentPosition = HeightVector * Mathf.Abs(timer * Speed * Time.deltaTime);
transform.position = originalPosition + currentPosition;
}
}