Search Unity

Weird Raycast Behavior

Discussion in '2D' started by Zei_SSB, Sep 12, 2019.

  1. Zei_SSB

    Zei_SSB

    Joined:
    Apr 7, 2019
    Posts:
    3
    Hey all!

    So I'm trying to set up a really simple grappling hook mechanic. I have a player circle with some anchor squares for right now. All I'm doing is doing the raycast so I can make sure it's actually hitting something, except I'm getting weird behavior on my raycast.

    I'm storing the raycast hits in a List<RaycastHit2D> and then just printing how many are in the list. Check the attached image for my setup and results.

    The three lines are just a Debug.DrawLine call set to show the Raycast. If you look in the console I get different amount of hits and I've no idea why. The amount of hits should always be 3 if I'm aiming through the bottom.

    Here's my raycast code with the Debug code in it.
    X and Y are player movement input

    Any ideas what's going on?

    Code (CSharp):
    1.  private void Shoot(float x, float y)
    2.     {
    3.         Vector2 newVector = new Vector2(x, y);
    4.         List<RaycastHit2D> raycastHit = new List<RaycastHit2D>();
    5.  
    6.         Physics2D.Raycast(playerPosition, playerPosition + newVector, noFilter.NoFilter(), raycastHit, maxDistance);
    7.  
    8.         switch (i)
    9.         {
    10.             case (0):
    11.                 Debug.DrawLine(playerPosition, playerPosition + newVector * maxDistance, Color.red, 3f);
    12.                 i++;
    13.                 break;
    14.  // ... and the two other switch statements for color and resetting i to 0
    15.         }
    16.  
    17.         foreach (RaycastHit2D hit in raycastHit)
    18.         {
    19.             if (hit == circleCollider)    // If it's the player, do nothing
    20.                 continue;
    21.  
    22.             if (hit.collider.tag == "Anchor")
    23.             {
    24.                 Debug.Log($"Hit {hit.collider.ToString()}");
    25.             }
    26.        }
    27.     }
    28.  
     

    Attached Files:

  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,917
    You're using the arguments for Physics2D.Linecast not Physics2D.Raycast . The second argument is the direction as the docs state.

    Shouldn't this be "hit.collider == circleCollider" ?
     
    Zei_SSB likes this.
  3. Zei_SSB

    Zei_SSB

    Joined:
    Apr 7, 2019
    Posts:
    3
    Thank you very much! I had gotten a similar setup to work in the past but somehow messed it up here.
     
    Last edited: Sep 12, 2019
    MelvMay likes this.