3D Jump Colission Detection

Hi,

Sorry if you think that this is a duplicate. I have been searching this site for every possible scenario for my game, but I have no luck finding it.

I am creating a 3D side scrolling bounce game. I want the user to be able to jump when they were on the ground (or hitting the ground after jumping, like the usual bounce game on your old phone).

I am using raycast to check for the colission, the pivot point of the sphere is on the center of it.

bool IsGrounded()
{
    RaycastHit hitInfo;
    if (Physics.Raycast(this.transform.position, Vector3.down, out hitInfo, this.transform.localScale.y / 2 - jumpTolerance))
    {
        return true;
    }          
    return false;
}

I am using the jump tolerance because dividing the raycast with two still giving too much raycast length.

On the fixed update, I am using this code.

if (attempToJump)
{
    Jump();            
}

The jump method is using the raycast checker.

void Jump()
{
    if (IsGrounded())
    {
        rigidbody.AddForce(0, jumpHeight, 0);
    }           
}

The attemptToJump variable is set inside the Update() method because it is suggested to write input related code inside the Update() method, and physics related code inside FixedUpdate() method. It just check for the GetKey(KeyCode.Space) and set the attemp to true, otherwise false.

The problem is, if I hold the space bar, it jumps, when it lands, it jumps again but with higher jump range.
Sometimes, it doesnt bounce when I keep pressing the space bar after it bounce naturally (Based on the physics material), or it jump lower than the desired jump height

Here is the screenshot of the simple game.

Thank you

If you don’t wish to be able to hold Space to continually jump, you’ll need to check for the OnDown trigger while you’re grounded. For example;

if (IsGrounded()&&Input.GetKeyDown("Space"))
{
rigidbody.AddForce(0, jumpHeight, 0);
}

As for the extra height you’re gaining from jumping when you land, my first guess would be to check your physics material on your colliders. If none are applied yet, try creating one and making sure that Bounce is set to 0.

If all else fails, try using a different velocity mode for your jump’s AddForce.
http://docs.unity3d.com/ScriptReference/ForceMode.html

VelocityChange is most often used for jumps as it applies the force while disregarding current mass and velocity. Hope this helps!