Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Raycast 2d Isn't going Like I want it to

Discussion in '2D' started by V4LK, Apr 14, 2021.

  1. V4LK

    V4LK

    Joined:
    Aug 5, 2020
    Posts:
    4
    Hi, I'm currently working on a 2D slingshot game. I'm using the player transform and a Direction transform in front of the player to draw a Raycast to detect where the player should go but after I moved the first time it just not working at all.
    I recorded a short clip to show the error:
     

    Attached Files:

  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,546
    You named your variable "direction" but that doesn't make it a direction, it's a point in space.

    Here's the docs for Physics2D.Raycast. The 2nd argument is a direction not a position in space. In your case it's a normalized "direction - startPos" but be careful here as those are 3D vectors. You should use 2D vectors otherwise any differences in Z can throw it out.

    There's Physics2D.Linecast which performs a check on a line-segment.
     
    V4LK likes this.
  3. V4LK

    V4LK

    Joined:
    Aug 5, 2020
    Posts:
    4
    Thx, but I still don't quite know how to do it. Im completely new to raycasts and vectors and stuff so a small example would be nice.
    And Im using Vector2, aren't they 2D Vectors?
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,546
    Okay but that's why we have docs. You specify a start position, direction, distance and mask.

    Code (CSharp):
    1.         startPos = playerTrans.position;
    2.         mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    3.         direction = (mousePos - startPos).normalized;
    4.  
    5.         RaycastHit2D WallCheck = Physics2D.Raycast(startPos, direction, Mathf.Infinity, ground);
    6.  
    Also note that unless you are absolutely sure this raycast will hit something, you should check to see if it does with "if (WallCheck) { <DO SOMETHING> }"

    Sorry yes, I just saw that you were transferring the Vector3 Transform.position to Vector2.
     
    V4LK likes this.
  5. V4LK

    V4LK

    Joined:
    Aug 5, 2020
    Posts:
    4
    Thank you so much