问题描述
我有一组对象,我允许我的玩家在零重力下在场景中抛掷。但是我想在一定高度后创建一种不可见的边界。到目前为止,当对象达到某个向上边界时,我一直在我的 FixedUpdate 中这样做...
GetComponent<Rigidbody>().veLocity = GetComponent<Rigidbody>().veLocity - Vector3.Project(GetComponent<Rigidbody>().veLocity,transform.up);
...这在某种意义上是有效的,但是因为它使用了transform.up,它从向上和向下运动中去除了速度,我需要将其限制为仅向上运动。这可能吗?
解决方法
也许您可以检查速度的 y 分量,如果它为正(向上)将其设置为 0?如果它是负数(向下)就保留它。
附注。我认为您应该获得一个引用刚体组件的变量,以尽量减少 GetComponent 调用。
Vector3 v = rb.velocity; //get the velocity
v.y = v.y > 0 ? 0 : v.y; //set to 0 if positive
rb.velocity = v; //apply the velocity
,
您可以检查位置是否达到阈值以及对象当前是否正在向上移动
[SerializeField] private Rigidbody rb;
[SerializeField] private float maxY;
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
var velocity = rb.velocity;
if(rb.position.y >= maxY && velocity.y > 0)
{
velocity.y = 0;
rb.velocity = velocity;
}
}