Search Unity

Raycast2D issues

Discussion in 'Physics' started by vvvey, Aug 13, 2016.

  1. vvvey

    vvvey

    Joined:
    Aug 13, 2016
    Posts:
    7
    Having read quite a few of them, I am well aware that there are a lot of threads on this subject. However, none of them seem to help me.

    I'm calculating a vision cone for my enemy and, if the player is in it, I try to check if there is a collider between them with Physics2D.Raycast

    The walls that can't be seen through are from a mesh, and have a mesh collider attached - see pic1 attached to this post. They are also on a specific layer, to which I'm trying to limit my Raycast.

    My code is pretty straight forward. if the enemy is facing the player, and the player is close enough, fire the raycast.
    Code (csharp):
    1.  
    2. if (distanceToPlayer < viewDistance && dirToPlayer == dir) {
    3.  
    4. //playerisincone,checkfor collision
    5.  
    6. LayerMask lm = LayerMask.NameToLayer ("WallCollisions");
    7. RaycastHit2D hit = Physics2D.Raycast( transform.position, (player.transform.position - transform.position).normalized , 1000, lm );
    8.  
    9. return true;
    10.  
    11. }
    12.  
    The hit always looks like this, regardless of direction, length and layermask.

    {UnityEngine.RaycastHit2D}
    centroid: {(0.0, 0.0)}
    collider: (null)
    distance: 0
    fraction: 0
    normal: {(0.0, 0.0)}
    point: {(0.0, 0.0)}
    rigidbody: (null)
    transform: (null)
    Non-public members:

    Right now I return true all the time, and just use the debugger to check the RayHit which is always at (0,0) with null values for everything. The enemy is not in the layer that I am limiting to.

    Also, note that in pic1, the guard is surrounded by the mesh, meaning that regardless of direction, there should be a hit within the distance specified..

    I'm sure that whatever I'm doing has a simple fix, but I can't figure it out..
     

    Attached Files:

    • pic1.png
      pic1.png
      File size:
      210.1 KB
      Views:
      818
    Last edited: Aug 13, 2016
  2. Duusty

    Duusty

    Joined:
    May 14, 2013
    Posts:
    56
    Because Raycast2D wont work with Meshcolliders which are 3D, you either need to use the normal threedimensional raycast. Or if you want to stay twodimensional with Raycast2D you could use BoxCollider2D or PolygonCollider2D.

    The Reason behind that is that unity3d uses different physic backends for 2D(box) and 3D(nvidia physix), which currently dont interact with each other

    Edit: Found a post with a more detailed description (http://answers.unity3d.com/questions/1134088/best-way-to-fix-get-2d-character-to-collide-with-a.html)
     
    Last edited: Aug 16, 2016
  3. vvvey

    vvvey

    Joined:
    Aug 13, 2016
    Posts:
    7
    Thank you so much! Using a polygon collider solved it!