【发布时间】:2018-07-29 18:14:35
【问题描述】:
目前我正在编写移动玩家的脚本。旨在沿 x 轴平滑运动。一切正常,但是当我编写一些代码来慢慢停止播放器时,出现了一些奇怪的行为。飞船永远不会完全停止,而是在原地晃动。
首先,我知道文档说,我在这里做的不好:
在大多数情况下,您不应直接修改速度,因为这会导致不切实际的行为。
我仍然想问是否有人知道为什么会发生这种情况,或者我如何避免在我的代码中使用rb.velocity *= BREAKING_FACTOR;。 (在刚体检查器中,速度每帧从 0 跳到 0.04 并返回)。
public class PlayerController : MonoBehaviour
{
private const float MAX_SPEED = 8f, FORCE_FACTOR = 20f, BREAKING_FACTOR = .9f;
private Rigidbody2D rb;
private void Start () { rb = this.GetComponent<Rigidbody2D> (); }
private void Update ()
{
var inputDirection = new Vector2 (0f, 0f);
if (Input.GetKey (KeyCode.A) && rb.velocity.x > -MAX_SPEED)
inputDirection += new Vector2 (-1f, 0f);
else if (Input.GetKey (KeyCode.D) && rb.velocity.x < MAX_SPEED)
inputDirection += new Vector2 (1f, 0f);
else
{
// rb.velocity *= BREAKING_FACTOR;
// If no force is added on the x-asis, the spaceship shall slow down
if (rb.velocity.x > 0f)
inputDirection += new Vector2 (-1, 0);
else if (rb.velocity.x < 0f)
inputDirection += new Vector2 (1, 0);
// Get it to stop completely when very slow
if (Mathf.Abs (rb.velocity.x) < 1f)
// The Thing you shouldn't do:
rb.velocity = new Vector2(0f, rb.velocity.y);
}
rb.AddForce (inputDirection * FORCE_FACTOR);
}
}
【问题讨论】:
-
如果速度低于某个阈值,您可以直接设置速度。