getALoadOfThisGuy
getALoadOfThisGuy

Reputation: 97

Forward and Sideways Player movement

So my friends and I are developing a game where you play as a snowball rolling down a hill avoiding obstacles. We're having trouble with our movement, however. We want our snowball to gains speed the larger it gets and the longer it goes without hitting something. Our forward movement is controlled by

void FixedUpdate(){
rb.velocity += Physics.gravity * 3f * rb.mass * Time.deltaTime; 

//to accelerate

rb.AddForce(0, 0, 32 * rb.mass);
}

We're applying a sideways force on key input

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);
            }
        }

The mass increases as the scale increases and vice versa.

The issue comes when the snowball gets larger than a certain scale. Once it hits that point it massively accelerates left and right while you push the keys then snaps back to its forward speed when you let go. I assume it's something to do with the mass and the way the applied forces are compounding.

Is there a better way to accelerate our snowball downhill or move it left and right? I've tried transform.Translate and transform.MovePosition, but they lead to choppy left and right movement.

Upvotes: 1

Views: 316

Answers (1)

Poultryghast
Poultryghast

Reputation: 58

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.

Upvotes: 1

Related Questions