Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Weird Raycast Behavior

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

  1. Zei_SSB


    Apr 7, 2019
    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>();
    6.         Physics2D.Raycast(playerPosition, playerPosition + newVector, noFilter.NoFilter(), raycastHit, maxDistance);
    8.         switch (i)
    9.         {
    10.             case (0):
    11.                 Debug.DrawLine(playerPosition, playerPosition + newVector * maxDistance,, 3f);
    12.                 i++;
    13.                 break;
    14.  // ... and the two other switch statements for color and resetting i to 0
    15.         }
    17.         foreach (RaycastHit2D hit in raycastHit)
    18.         {
    19.             if (hit == circleCollider)    // If it's the player, do nothing
    20.                 continue;
    22.             if (hit.collider.tag == "Anchor")
    23.             {
    24.                 Debug.Log($"Hit {hit.collider.ToString()}");
    25.             }
    26.        }
    27.     }

    Attached Files:

  2. MelvMay


    Unity Technologies

    May 24, 2013
    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


    Apr 7, 2019
    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.