- Home /
Jump problem
Hi, I am having trouble making a jump which allows the player to either hold the screen to jump continuously or tap the screen once and just jump once. My script below is what I am using but since GetMouseButton(0) is being called more than once while the player is on the ground the rigid body is getting the force added more than once too which means the player flies way up into the air. Is there a way which I can call the rigidbody.AddForce() just once using this method or will I need to use a different method? thanks
var jump : boolean;
var grounded : boolean = false;
var groundCheck : Transform;
var groundRadius : float = 0.2f;
var whatIsGround : LayerMask;
var myRigidbody : Rigidbody2D;
function FixedUpdate(){
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
}
function Update(){
if(Input.GetMouseButton(0)){
if(grounded){
jump = true;
}
}
if(jump){
myRigidbody.AddForce(new Vector2(0, 1500f * Time.fixedDeltaTime));
jump = false;
}
}
Answer by Hanoble · Mar 21, 2017 at 06:54 PM
You should debug your code (either through logs or breakpoints), but what I would assume is happening is that for several frames your grounded check is still true and thus the AddForce is being called several times.
The code you have is an okay starting point and one solution would be to implement something like a "minimum jump timer", which kicks off a timer and manages a "canJump" bool for you. This will need to be tweaked until it feels right with your grounded check, but something like this would work.
//Duration is a public class variable you pass in
private IEnumerator DisableJump(float duration)
{
float timer = duration;
canJump = false;
while(timer > 0.0f)
{
timer -= time.deltaTime;
yield return null;
}
canJump = true;
}
You would then call this using:
StartCoroutine(DisableJump(jumpTimer));
Lastly, you would want to remove the setting of the jump bool from the update logic and check to make sure you can jump, something like this:
function Update()
{
if(Input.GetMouseButton(0))
{
if(grounded && canJump)
{
myRigidbody.AddForce(new Vector2(0, 1500f * Time.fixedDeltaTime));;
StartCoroutine(DisableJump(jumpTimer));
}
}
}
Unity also has a free character controller, and there are several others you can find out there for free, where they tackle similar issues. Looking at how they handle grounded checks and jump logic would be a good training exercise and something I would advise if you have the time for it.
Your answer
Follow this Question
Related Questions
Character doesn't fall back down when jumping 0 Answers
,Rotate a gameobject around another while being attracted by its gravity 1 Answer
I'm so lost trying to add a force towards the nearest collder with tag "x" 0 Answers
how to make my character stay stable after hit? 2 Answers
The character velocity changes while the rigidbody is kinematic 1 Answer