Hello, I’m making a plat-former game Mario style and i want to limit the player to jump once when on ground, but with my current algorithms the player can jump unlimited times.
My character (which the players control) script is:
//floats that sets current speed, jump power, and max speed respectively
public float speed = 50f;
public float jumpPower = 150f;
public float maxSpeed = 3f;
//bool that sets if player is colliding with ground
public bool onGround = true;
private Rigidbody2D rg2d;
private Animator anim;
void Start ()
{
rg2d = gameObject.GetComponent<Rigidbody2D> ();
anim = gameObject.GetComponent<Animator> ();
}
void Update ()
{
anim.SetFloat ("Speed",Math.Abs( Input.GetAxis ("Horizontal")));
anim.SetBool ("On Ground", onGround);
//flips the player animation according to his movement
if (Input.GetAxis ("Horizontal") < -0.1f)
{
transform.localScale = new Vector3 (-1, 1);
}
if (Input.GetAxis ("Horizontal") > 0.1f)
{
transform.localScale = new Vector3 (1, 1);
}
//if the player isn't on ground and pressing JumpButton, player will jump
if (Input.GetButtonDown ("Jump") && onGround)
{
rg2d.AddForce (Vector2.up * jumpPower);
}
}
void FixedUpdate ()
{
float h = Input.GetAxis ("Horizontal");
//moving player on X axis
rg2d.AddForce ((Vector2.right * speed) * h);
//limiting player movement on X axis
if (rg2d.velocity.x > maxSpeed)
{
rg2d.velocity = new Vector2 (maxSpeed, rg2d.velocity.y);
}
if (rg2d.velocity.x < -maxSpeed)
{
rg2d.velocity = new Vector2 (-maxSpeed, rg2d.velocity.y);
}
}
and i putted right under the character a child gameObject named GroundCheck that will change onGround bool within certain conditions:
void Start ()
{
player = gameObject.GetComponentInParent<Player> ();
}
//this GroundCheck script purpose is to change player.onGround bool according to certain conditions.
//the bool onGround will be positive when GroundCheck is colliding with the ground and negative when not colliding with the ground.
void OnTriggerEnter2D(Collider2D other)
{
player.onGround = true;
}
void onTriggerStay2D(Collider2D other)
{
player.onGround = true;
}
void onTriggerExit2D(Collider2D other)
{
player.onGround = false;
}
But when i run the game, the player can jump unlimited times want and can fly out of the window.
Could someone please notice the problem I have with the scripting and correct me?