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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

How to detect if player is on layer

Discussion in 'Scripting' started by Vexer, May 15, 2018.

  1. Vexer

    Vexer

    Joined:
    Feb 24, 2016
    Posts:
    187
    Hey guys im trying to find a way to check if my player is on the ground by using a layermask
    i thought i could just copy and paste my 2d code to my 3d project but that doesn't seem to work...
    this is my 2d code:
    Code (csharp):
    1.  isGrounded = Physics2D.IsTouchingLayers(col, whatIsGround);
    How could i convert this into something that would work for a 3d game?
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,113
    It's similar, but you'd use Raycast/SphereCast/CapsuleCast instead. The basic idea is that you start from a point just about the character's feet, and spherecast downward, and see if you hit the ground. You can adjust the layermask used to decide what should be considered "ground". Here's the approach used by the StandardAssets rigidbody controller.

    Code (CSharp):
    1.  
    2.         private void GroundCheck()
    3.         {
    4.             m_PreviouslyGrounded = m_IsGrounded;
    5.             RaycastHit hitInfo;
    6.             if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
    7.                                    ((m_Capsule.height / 2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
    8.             {
    9.                 m_IsGrounded = true;
    10.                 m_GroundContactNormal = hitInfo.normal;
    11.             }
    12.             else
    13.             {
    14.                 m_IsGrounded = false;
    15.                 m_GroundContactNormal = Vector3.up;
    16.             }
    17.             if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
    18.             {
    19.                 m_Jumping = false;
    20.             }
    21.         }
    22.  
    23.  
     
  3. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    An alternative method might be to have a trigger collider underneath the player. Then set
    m_IsGrounded = true;
    in OnTriggerEnter() and set to false in OnTriggerExit().