- Home /
Character jumping at random heights. What in my code is causing this?
Hey, does anyone know why this code is causing my character to jump at varying heights? It isn't proportional to how long the button is held and seems random.
public class DodgeManController : MonoBehaviour {
public float maxSpeed = 10.0f;
public float jumpForce = 5.0f;
bool grounded;
public float groundRadius = 0.2f;
public Transform groundCheck;
public LayerMask whatIsGround;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update(){
if (grounded && Input.GetAxis ("Jump") > 0) {
rigidbody2D.AddForce (Vector2.up * jumpForce,ForceMode2D.Impulse);
}
}
void FixedUpdate () {
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
}
}
Answer by Alex_May · Feb 01, 2015 at 11:19 PM
Put your AddForce code in FixedUpdate. Since you can't guarantee how often Update() is called, your AddForce code could be getting called multiple times or not at all between physics updates. Anything that interacts with the physics system should be put in FixedUpdate, which is guaranteed to be called at regular intervals.
It still seems to be varying the jump height every now and again, although it seems less extreme now.
Poll the input in Update(), rather than FixedUpdate(), and store the result in a bool. Then you can test that bool in FixedUpdate, and set it to false after processing it. That way your input will only get used once. What's happening is that since FixedUpdate might (or might not) run multiple times in between Updates, and Input is only updated when Update happens (rather than for FixedUpdate), your AddForce code is being run multiple times.
Thanks, I've managed to fix it. Thanks for all the help.