- Home /
restrict number of double jumps
Hi, i am trying to set a limit of doubles jumps available to the player. so for this code i am using i have set the limit to 5 and every time the player double jumps it is reduced by one. so that when it reaches zero then cannot use double jump anymore. however it seems to have back fired and allows the player to continuously jump in the air, even when not on the ground. please help. using UnityEngine; using System.Collections;
public class CharacterMove : MonoBehaviour {
public float speed = 6.0f;
Transform groundCheck;
private float overlapRadius = 0.2f;
public LayerMask whatIsGround;
private bool grounded = false;
private bool jump = false;
public float jumpForce = 700f;
private bool doubleJump = false;
public int dJumpLimit = 5;
void Awake()
{
rigidbody2D.fixedAngle = true;
}
void Start()
{
groundCheck = transform.Find ("groundcheck");
PlayerPrefs.SetInt ("doublejumps", dJumpLimit);
}
void Update()
{
//if (Input.GetKeyDown (KeyCode.Space)){
// jump = true;
//}
if (Input.GetMouseButtonDown (0))
{
jump = true;
}
}
void FixedUpdate()
{
//check if character is grounded
grounded = Physics2D.OverlapCircle (groundCheck.position, overlapRadius, whatIsGround);
//reset doublejump when player is on the ground
if (grounded)
doubleJump = false;
//determine if player can jump
bool canJump = (grounded || !doubleJump);
if (jump && canJump)
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x,0);
rigidbody2D.AddForce(new Vector2(0, jumpForce));
if(!grounded && dJumpLimit >= 1)
{
doubleJump = true;
dJumpLimit--;
}
else if(!grounded && dJumpLimit <= 0)
{
doubleJump = false;
}
}
jump = false;
//apply forward movement
rigidbody2D.velocity = new Vector2 (speed, rigidbody2D.velocity.y);
}
}
Is GroundCheck parented to your GameObject(e.g. character)? If it is not, it will stay on the groun and OverLap circle will always return true. Also, you are not restoring dJumpLimit back to 5, thus your character will be able da 5-jump only once.
Answer by David-Berger · Jul 21, 2014 at 05:39 PM
In the case you have set up your GameObject properly according to the GroundCheck you possible can adjust your code to support proper change of the doubleJump flag.
[...]
//check if character is grounded
grounded = Physics2D.OverlapCircle (groundCheck.position, overlapRadius,whatIsGround);
//reset doublejump when player is on the ground
if (grounded)
doubleJump = false;
//deactivate double jump when no jumps are available
if (dJumpLimit < 1)
doubleJump = true;
//determine if player can jump
bool canJump = (grounded || !doubleJump);
if (jump && canJump)
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x,0);
rigidbody2D.AddForce(new Vector2(0, jumpForce));
if(!doubleJump && !grounded) {
doubleJump = true;
dJumpLimit--;
}
}
jump = false;
[...]
Hope this helps.
thanks so much this worked exactly how i wanted. it won't let me vote your answer as i don't have a rep level of 15 yet.