0
votes

I have a character in Unity that I'm using a raycast to have him jump. But even when the raycast doesn't hit the ground (I can see the ray with the debug output) the player still can jump. Any ideas why the ray is always thinks it is colliding? Could the ray be hitting my character collider, causing it to be true? Ive been search online for hours and nothing I find is fixing the situation. Here is my code:

void FixedUpdate()
{
    Ray ray = new Ray();
    RaycastHit hit;
    ray.origin = transform.position;
    ray.direction = Vector3.down;
    bool output = Physics.Raycast(ray, out hit);
    Debug.DrawRay(ray.origin, ray.direction, Color.red);
    if (Input.GetKey(KeyCode.Space) && output)
    {
        r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);

    }

}
1
have you tried moving the ray.origin to be outside of your character collider?Kolichikov
Yes, so when I put the ray lower (below the character and the ground) there is no jumping, which makes sense. But It i just put it below the character (still above the ground, as close to level with characters feet as possible), it never detects the ground and constantly allows jumpingSJR59
also when I put the ray above my character, like far a above, it still allows for jumping...SJR59

1 Answers

2
votes

Could the ray be hitting my character collider?

Yes, that is possible.

This is actually problem that can easily be solve with Debug.Log.

Put Debug.Log("Ray Hit: " + hit.transform.name); inside the if statement and it will show what Object is blocking the Raycast.

If this is indeed the problem, this post describes many ways to fix it. That answer and code changes a little bit because this question is about 3D not 2D. Just use layer. Put your player in Layer 9 then the problem should go away.

void FixedUpdate()
{
    int playerLayer = 9;

    //Exclude layer 9
    int layerMask = ~(1 << playerLayer); 


    Ray ray = new Ray();
    RaycastHit hit;
    ray.origin = transform.position;
    ray.direction = Vector3.down;
    bool output = Physics.Raycast(ray, out hit, 100f, layerMask);



    Debug.DrawRay(ray.origin, ray.direction, Color.red);
    if (Input.GetKey(KeyCode.Space) && output)
    {
        r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);
        Debug.Log("Ray Hit: " + hit.transform.name);
    }
}