Search Unity

RigidBody2D.Cast Not Working on One Side of Collider

Discussion in '2D' started by hordric, May 23, 2018.

  1. hordric

    hordric

    Joined:
    Jun 19, 2017
    Posts:
    1
    Hi all,

    I am currently designing a grab system, where a player can grab a "MovableObject" if they are holding down the grab button and are near enough to it. I am using RigidBody2D.Cast to check to make sure the player is close enough to the MovableObject in order to grab it.

    The problem is, when the player is standing to the left of the object, the method works fine. However, when the player is standing to the right of the object, the method does not work at all. Here is the method code:

    Basically, the code is supposed to cast the RigidBody left and right to see if it would collide with the Movable Object, and if yes, it returns true only if the player is holding down the grab button.

    Code (CSharp):
    1. public bool IsGrabbing(MovableObject movObj) {
    2.         if (!isTryingToGrab) { return false; }
    3.  
    4.         RaycastHit2D[] results1 = new RaycastHit2D[16];
    5.         RaycastHit2D[] results2 = new RaycastHit2D[16];
    6.  
    7.         Vector2 direction1 = Vector2.left;
    8.  
    9.         Vector2 direction2 = Vector2.right;
    10.  
    11.         int count1 = rigidbody.Cast(direction1, contactFilter, results1, grabDistance);
    12.         int count2 = rigidbody.Cast(direction2, contactFilter, results2, grabDistance);
    13.  
    14.         if (count1 <= 0 || count2 <= 0) { return false; }
    15.  
    16.         bool isObjHit = false;
    17.  
    18.         for (int i = 0; i < count1; i++) {
    19.  
    20.             if (results1[i] == movObj) { isObjHit = true; }
    21.         }
    22.  
    23.         for (int i = 0; i < count2; i++) {
    24.  
    25.             if (results2[i] == movObj) { isObjHit = true; }
    26.         }
    27.  
    28.         return isTryingToGrab && isObjHit;
    29.     }
    Any help / ideas on what I could try would be greatly appreciated!
    By the way, I put debug statements inside of the results1 and results2 loops, and do indeed print out, so it is not a problem with "isTryingToGrab" (besides, it works on the left side anyway).
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,497
    These don't look correct. The results array is an array of RaycastHit2D structs, not MovableObject types (not sure what this type and therefore how equality would work).

    You get objects by using RaycastHit2D.collider or Raycasthit2D.rigidbody.