- Home /
The question is answered, right answer was accepted
AddForce adding together on 2 button presses
I've been making a platformer for some time, and the player can both jump and have an upwards force applied so the player can hover.
However, when I press jump, then immediately press gravity, the forces are added together and the player goes a lot higher than intended, and this would break the game in make instances.
How can I detect that I'm jumping so that if the player presses the gravity button moments later the two forces aren't added together?
I've copied in the code for the problem:
function FixedUpdate () {
if(grounded == true){
if (jumpKeyPressed){
if(inwater == false){
rigidbody.velocity.y += jumpSpeed;
}else{
rigidbody.velocity.y -= (jumpSpeed-(jumpSpeed/3));
}
}
}
if(Gravity == false){
Physics.gravity = Vector3(0, gravity, 0);
}
if(Gravity == true){
Physics.gravity = Vector3(0, -gravity, 0);
}
jumpKeyPressed = false;
if (rigidbody.IsSleeping()){
rigidbody.WakeUp();
}
grounded = false;
}
Any ideas would be appreciated.
Answer by Julien-Lynge · Dec 07, 2013 at 07:10 PM
I didn't see a question in there. I'm guessing you want to disallow the player from jumping and turning off gravity at the same time? In which case, can't you just add a check in your FixedUpdate? If jump, do x. If jump and gravity, do y, which removes the gravity effect from the jump effect.
I added the question "How can I detect that I'm jumping so that if the player presses the gravity button moments later the two forces aren't added together?"
But i don't know how to limit the force being added; I guess that could be the route of issue.
Oh, I think I may see - you want to know not if the player pressed jump this frame, but if the player pressed jump in a previous frame and hasn't yet come back in contact with the ground?
Isn't that what your grounded bool is for? Can you check that and disallow changing gravity while it's true?
yeah; woops.
checked gravity was true then included if(grounded == true){ jumpSpeed = 0; }else{ jumpSpeed = 40; }
just about does the trick.
Awesome! I've marked the answer as correct and closed the question.