Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Problem with raycast

Discussion in 'Scripting' started by MagicFrame, May 8, 2014.

  1. MagicFrame

    MagicFrame

    Joined:
    Jul 18, 2013
    Posts:
    42
    Hi all,

    I am creating a script to detect the floor and ceiling, but not working correctly, the problem is that when it detects the ground the variable "Isgrounded" switch to true, but when it does not detect the ground variable "IsGrounded" does not change false.

    this is my code


    Code (csharp):
    1. if(Physics.Raycast(detectFloorDown, out hitDown, csextents.y +  raycastOffsetDown))
    2.         {
    3.  
    4.             if(hitDown.collider.name == "ground")
    5.             {
    6.                 grounded = true;
    7.             }
    8.             else
    9.             {
    10.                 grounded=false;
    11.                
    12.             }

    the code never returns false when collision with the ground switch to true and is always true
     
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    Whenever the raycast hits nothing, the grounded flag has to be set to false as well.

    Code (csharp):
    1. if(Physics.Raycast(detectFloorDown, out hitDown, csextents.y + raycastOffsetDown))
    2. {
    3.     if(hitDown.collider.name == "ground")
    4.     {
    5.         grounded = true;
    6.     }
    7.     else
    8.     {
    9.         grounded = false;
    10.     }
    11. } else {
    12.     grounded = false;
    13. }
     
  3. MagicFrame

    MagicFrame

    Joined:
    Jul 18, 2013
    Posts:
    42
    Hi Dantus, thanks for your help, Now another problem has appeared: (, now works fine, but when it detects the ground, "IsGrounded" switch to true, but then switch to being false even colliding with the ground.
     
  4. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  5. MagicFrame

    MagicFrame

    Joined:
    Jul 18, 2013
    Posts:
    42
    hi, yes, I'm using Debug.DrawLine, and the ray is hitting the ground, strikes cuanod "IsGrounded" switch to true, but then immediately switch to false, because it does not hold true if the ray is inside the collider.
     
  6. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
    You just formulated the solution yourself. Make sure the ray is not inside of the collider by making sure the raycast starts slightly higher.