Search code examples
unity-game-engineunity3d-2dtools

Gravity dramatically changing when adding player controls


so if when I add my rigidbody2D the gravity works as it normally would. my player sprite falls down and it's velocity downwards increases. Once I add some very simple player controls it seems to almost be throttled? bumping up the gravity to something like 50 still doesn't feel the same as gravity=1 (default settings) without my player control script. here's my code.

public class playerControlls : MonoBehaviour {

public float maxSpeed;

void Update(){
    float moveH = Input.GetAxis ("Horizontal");
    Vector3 movement = new Vector3 (moveH, 0.0f, 0.0f);
    rigidbody2D.velocity = movement * maxSpeed;
}
}

Solution

  • You are setting you sprites velocity to be limited by maxSpeed, this includes its falling speed.

    rigidbody2D.velocity = movement * maxSpeed;
    

    Means the sprite will never achieve downwards speeds that exceed maxSpeed. When setting the movement vector, include rigidbody.velocity.y.

    void Update() {
        float moveH = Input.GetAxis ("Horizontal");
        Vector3 movement = new Vector3 (moveH, 0.0f, 0.0f);
        movement *= maxSpeed;
        movement.y = rigidbody2D.velocity.y; //movement vector now maintains current falling speed
        rigidbody2D.velocity = movement;
    }