- Home /
Jumping Ball
Im trying to get my ball to jump but sometimes it just doesnt jump. The boolean turns it self off when hitting the spacebar but doesnt jump and stays on the ground. Here's my script.
bool canJump = false;
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "ground") {
canJump = true;
Debug.Log("test");
}
}
void Movement()
{
move = Input.GetAxis ("Horizontal");
rigidbody.velocity = new Vector3 (move * 5f, rigidbody.velocity.y);
if(Input.GetKeyDown("space"))
{
if(canJump)
{
rigidbody.AddForce(new Vector3(0,10),ForceMode.Impulse);
canJump =false;
}
}
}
Answer by _Gkxd · Apr 07, 2015 at 02:08 AM
A reliable way to code jumping is to cast a ray downwards for a short distance and see if it hits the ground.
The code that you have assumes that whenever you press the jump key, you leave the collision with the ground, and after some time, you will enter collision again, triggering OnCollisionEnter
. This isn't always true though.
If you press the jump key but don't leave collision with the ground, then you won't enter collision with the ground, meaning that canJump
won't be set to true even if you're on the ground. For example, if you try to jump, but you're blocked by a ceiling and don't actually leave the ground, you won't be able to jump anymore. (This is definitely a problem that can happen in your code, but I'm not sure if it's the problem that you're having right now.)
The general raycasting idea is to use Physics.Raycast with a ray from your player's position downwards, setting maxDistance appropriately so that the ray ends at the bottom of your player. This ray should ideally collide with the ground only when your player is touching the ground.
When you press the jump key, set some boolean isInAir
to true. Whenever isInAir
is true, perform the raycast, and if the ray hits the ground, set isInAir
to false.
But since it is a ball and is in constant turning motion, wont casting a Physics.Raycast downward turn the Ray left/right/up thus making the ray not work depending on how you land?
The documentation for raycast specifies that starting point of the ray is in world coordinates, so it would make sense if the direction is in world orientation. You can always use Debug.DrawRay to see what ray you are casting in the editor.
I would find it strange if the direction is affected by the orientation of the object that you're casting from.
I used your method and placed 4 raycast's. I kinda already knew the method but i just thought maybe there was another way. Accpeted your method as Answer :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to make a ball jump? 2 Answers
Player stucken in the wall while jumping 2D 1 Answer
Character not jumping high enough 1 Answer