Search Unity

2D Linecasting

Discussion in '2D' started by zxng, Jan 25, 2015.

  1. zxng

    zxng

    Joined:
    Jan 22, 2015
    Posts:
    5
    Hi guys!

    I've been trying to check whether my character is grounded by using Physics2D.Linecast.

    Code (CSharp):
    1.         Vector2 playerPos = new Vector2 (GameObject.Find ("Player").transform.position.x, GameObject.Find ("Player").transform.position.y);
    2.         Vector2 groundPos = new Vector2 (GameObject.Find ("Player").transform.position.x, GameObject.Find ("Player").transform.position.y - 1.5f);
    3.         bool grounded;
    4.         int groundMask = 1 << LayerMask.NameToLayer("GroundLayer");
    5.  
    6.         Debug.DrawLine(playerPos, groundPos, Color.magenta);
    7.  
    8.         grounded = Physics2D.Linecast (playerPos, groundPos, groundMask);
    9.         return grounded;
    I'm trying to detect the ground below the player by linecasting "1.5f" directly below the player and returning the info.

    However, the issue is that it always returns true for grounded, no matter whether I'm in the air or not.

    *UPDATE: I played around with it for a while and now it's always returning false. Anyone has any tips on what to look out for in terms of linecasting?"
     
    Last edited: Jan 25, 2015
  2. zxng

    zxng

    Joined:
    Jan 22, 2015
    Posts:
    5
    I found out that because I was instantiating my random ground tiles into the scene, they were not in the GroundLayer and therefore the collider always returns false.

    I'm still looking to see how to change the layers of my instantiated tiles.
     
  3. zxng

    zxng

    Joined:
    Jan 22, 2015
    Posts:
    5
    Okay, basically I used "object.layer = LayerMask.NameToLayer("GroundLayer")" to move all my instantiated tiles into the ground layer when they get spawned out.

    Hope this'll helped someone else with the same issues I had!
     
  4. Naphier

    Naphier

    Joined:
    Aug 4, 2014
    Posts:
    114
    You could also check the RaycastHit2D collider to see if it is the correct object or object with tag, but layer masks are much more efficient since it's not colliding with everything!