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