問題描述
向前和橫向球員運動 (Forward and Sideways Player movement)
因此,我和我的朋友們正在開發一款遊戲,您可以在遊戲中扮演滾雪球從山上滾下來避開障礙物的遊戲。然而,我們的運動遇到了麻煩。我們希望我們的雪球越快越快,越長越不會撞到任何東西。我們的前進運動由
void FixedUpdate(){
rb.velocity += Physics.gravity * 3f * rb.mass * Time.deltaTime;
//to accelerate
rb.AddForce(0, 0, 32 * rb.mass);
}
我們在按鍵輸入上施加側向力
if (Input.GetKey(ControlManager.CM.left))
{
if (rb.velocity.x >= ‑15 ‑ (rb.mass * 8))
{
rb.AddForce(Vector3.left * sidewaysForce * (rb.mass * .5f), ForceMode.VelocityChange);
}
}
if (Input.GetKey(ControlManager.CM.right))
{
if (rb.velocity.x <= 15 + (rb.mass * 8))
{
rb.AddForce(Vector3.right * sidewaysForce * (rb.mass * .5f), ForceMode.VelocityChange);
}
}
質量隨著規模的增加而增加,反之亦然。
當雪球變得大於一定規模時,問題就出現了。一旦達到該點,它就會在您按下按鍵時向左和向右大幅加速,然後在您鬆開時迅速恢復到其前進速度。我認為這與質量和施加的力複合的方式有關。
有沒有更好的方法來加速我們的雪球下坡或左右移動?我嘗試過 transform.Translate 和 transform.MovePosition,但它們會導致左右移動不連貫。
參考解法
方法 1:
For one, most movement code should multiply the velocity by Time.deltaTime
. In a hypothetical game, if you increased the velocity by a certain amount each frame, then somebody with a beefy 60 fps computer will go twice as fast as a poor 30 fps laptop gamer because they will accelerate less frequently. In order to fix this, we multiply acceleration by Time.deltaTime
, which is the time since the last frame.
Instead of this code, where framerate would determine speed;
Vector3 example = new Vector3(1,1,1);
void Update()
{
rb.AddForce(example);
}
We would use this code. If the framerate is half as much, Time.deltaTime
will be twice as much, so the acceleration will be constant for everyone using it.
Vector3 example = new Vector3(1,1,1);
void Update()
{
rb.AddForce(example * Time.deltaTime);
}
There may be another source of this problem, although getting rid of frame‑rate dependencies is a good place to start. It looks like you already have used Time.deltaTime
for downward velocity, but not for sideways movement. Even if it doesn't fix the problem, using Time.deltaTime is essential for any consistent game.
(by getALoadOfThisGuy、Poultryghast)