[英]How to cap velocity in Unity 3D using AddForce with ForceMode.VelocityChange
I am working on a player controller and having trouble with limiting the character's velocity.我正在研究玩家 controller 并且无法限制角色的速度。 The character seems to accelerate indefinitely.
角色似乎无限加速。
I am updating the character's velocity using rb.AddForce(movement * movementSpeed, ForceMode.VelocityChange)
, where movement
is a normalized Vector3
(with values only for x
and z
) and movementSpeed
is a public float giving the desired movement speed.我正在使用
rb.AddForce(movement * movementSpeed, ForceMode.VelocityChange)
更新角色的速度,其中movement
是归一化的Vector3
(仅具有x
和z
的值),而movementSpeed
速度是提供所需运动速度的公共浮点数。 I realize that it would be trivial to cap the character's velocity by setting it directly but I'm under the impression that setting rb.velocity
directly is bad practice (which I'm not entirely sure is true).我意识到通过直接设置来限制角色的速度是微不足道的,但我的印象是直接设置
rb.velocity
是不好的做法(我不完全确定这是真的)。
My fixed update function:我的固定更新 function:
private void FixedUpdate()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
movement.Normalize();
rb.AddForce(movement * movementForce, ForceMode.VelocityChange);
}
I have tried adding a conditional statement checking if the velocity is greater than the desired maximum and, if true, adding a force in the opposing direction.我尝试添加一个条件语句,检查速度是否大于所需的最大值,如果为真,则在相反方向添加一个力。 This results in stuttering.
这会导致口吃。 The character's velocity is reset to 0 and forced to accelerate again.
角色的速度被重置为 0 并被迫再次加速。
Vector3 currMovement = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
float currMagnitude = currMovement.magnitude;
if (currMagnitude > movementSpeed) {
rb.AddForce(currMovement * (-1 * movementSpeed / currMagnitude), ForceMode.VelocityChange);
}
Any help would be greatly appreciated?任何帮助将不胜感激?
rb.AddForce(movement, ForceMode.VelocityChange)
?rb.AddForce(movement, ForceMode.VelocityChange)
时如何限制速度?rb.AddForce
or can I directly set rb.velocity
?rb.AddForce
还是可以直接设置rb.velocity
?I don't see anything wrong with setting the velocity directly, especially when it comes to capping velocity.我认为直接设置速度没有任何问题,尤其是在限制速度方面。 I think people tend to visualize velocity better when they're adding a force in a direction rather than directly setting it, but no, in short, I don't think it's bad practice.
我认为当人们在一个方向上增加一个力而不是直接设置它时,他们倾向于更好地可视化速度,但不,简而言之,我不认为这是不好的做法。
Have a look at Unity's Mathf.Clamp documentation.查看 Unity 的Mathf.Clamp文档。 I'd do something like:
我会做类似的事情:
private void FixedUpdate()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
movement.Normalize();
rb.AddForce(movement * movementForce, ForceMode.VelocityChange);
rb.velocity = new Vector3(Mathf.Clamp(rb.velocity.x, -SomeMaximumVelocity, SomeMaximumVelocity),
rb.velocity.y,
Mathf.Clamp(rb.velocity.z, -SomeMaximumVelocity, SomeMaximumVelocity));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.