For the most part, my jump script works. However, I noticed that there is a rare exception, namely that if the jump button is pressed in the exact moment that the player hits the ground, the player will sometimes be unable to jump. The timing to repeat this bug is strict but I can’t figure out what is causing the problem. I am wondering if it has to do with the timings for when Unity calls the functions OnTriggerEnter2D and Update. For reference here is my player script:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float speed = 50f;
public float maxSpeed = 3f;
public float jumpPower = 200f;
public bool grounded;
private Rigidbody2D rigidBody;
private Animator animator;
void Start () {
rigidBody = gameObject.GetComponent<Rigidbody2D>();
animator = gameObject.GetComponent<Animator>();
}
void Update () {
animator.SetBool("Grounded", grounded);
animator.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if (Input.GetAxis("Horizontal") < -0.1f) {
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1f) {
transform.localScale = new Vector3(1, 1, 1);
}
if (Input.GetButtonDown("Jump") && grounded)
{
rigidBody.AddForce(Vector2.up * jumpPower);
}
}
void FixedUpdate()
{
//Horizontal and Vertical Input
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Fake friction
Vector3 friction = rigidBody.velocity;
friction.x *= 0.75f;
if (grounded) {
rigidBody.velocity = friction;
}
//Movement
rigidBody.AddForce(Vector2.right * speed * h);
if (rigidBody.velocity.x > maxSpeed) {
rigidBody.velocity = new Vector2(maxSpeed, rigidBody.velocity.y);
}
if (rigidBody.velocity.x < -maxSpeed) {
rigidBody.velocity = new Vector2(-maxSpeed, rigidBody.velocity.y);
}
}
}
And here is the script that checks for ground collision:
using UnityEngine;
using System.Collections;
public class GroundCheck : MonoBehaviour {
private Player player;
// Use this for initialization
void Start() {
player = gameObject.GetComponentInParent<Player>();
}
void OnTriggerEnter2D(Collider2D collider) {
player.grounded = true;
}
void OnTriggerStay2D(Collider2D collider) {
player.grounded = true;
}
void OnTriggerExit2D(Collider2D collider) {
player.grounded = false;
}
}
Any ideas?