【发布时间】:2018-09-15 22:26:53
【问题描述】:
我如何创建一个统一的弹跳球,它弹跳到相同的高度,并且我可以让它更快或更慢地落下?有人告诉我使用:
heightVector * |sin(time * speed)|
但我不知道在哪里插入它。我对这些事情真的很菜鸟。救命!
【问题讨论】:
我如何创建一个统一的弹跳球,它弹跳到相同的高度,并且我可以让它更快或更慢地落下?有人告诉我使用:
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 变量。然后你需要在每次Update 调用时添加Time.deltaTime。
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;
}
}
【讨论】:
The same logic applies to the bounciness model. Nvidia PhysX doesn’t guarantee perfect energy conservation due to various simulation details such as position correction. So for example when the bounciness value of an object affected by gravity is 1 and is colliding with ground that has bounciness 1 expect the object to reach at higher positions than then initial one.