Search Unity

raycast2d

Discussion in 'Physics' started by Tempest74, Jan 6, 2019.

  1. Tempest74

    Tempest74

    Joined:
    May 17, 2017
    Posts:
    92
    I need some help to understand how to use raycast2d. I am using the top down kind of map (you see everything from above), my map is compose from tiles and every one of them has its own layer (or no layer at all). My walkableMask contains elements so it isn't empty. But the hit variable does not return any value. Could you help me figure why?
    Code (CSharp):
    1. for(int x = 0; x < gridSizeX; x++)
    2.         {
    3.             for(int y = 0; y < gridSizeY; y++)
    4.             {
    5.                 Vector3 worldPoint = worldButtomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius);
    6.                 bool walkable = !(Physics2D.OverlapCircle(worldPoint, nodeRadius, unwalkableMask));
    7.  
    8.                 int movementPenalty = 0;
    9.  
    10.                 if (walkable)
    11.                 {
    12.                     Vector3 rayOrigin = worldPoint + Vector3.up * 50;
    13.                     Ray2D ray = new Ray2D(new Vector2(rayOrigin.x, rayOrigin.y), Vector2.down);
    14.                     RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 100, walkableMask);
    15.                     Debug.Log(hit.collider.gameObject.layer != 0 ? hit.collider.gameObject.layer : 0);
    16.                     if (hit)
    17.                     {
    18.                         walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out movementPenalty);
    19.                         Debug.Log(movementPenalty);
    20.                     }
    21.                 }
    22.                 grid[x, y] = new Node(walkable, worldPoint, x, y, movementPenalty);
    23.             }
    24.         }
     

    Attached Files:

  2. WashingMachine

    WashingMachine

    Unity Technologies

    Joined:
    Mar 23, 2017
    Posts:
    24
    What exactly are you trying to do? Are you trying to figure out what terrain the player is walking on?