Search Unity

Raycast2D first object hit

Discussion in 'Scripting' started by Juozukas, Sep 20, 2017.

  1. Juozukas

    Juozukas

    Joined:
    Sep 2, 2017
    Posts:
    4
    Hey there,

    The problem I have here is basically this.

    https://imgur.com/a/bLkxh

    Whenever I shoot the raycast I only want it to return me the first object he is colliding with.

    Any suggestions how to acomplish it ? Heres my code ( both gameObjects are tagged as "Destroy")

    Code (CSharp):
    1. Void Raycasting(){
    2.  
    3. {
    4.  
    5.  
    6.        
    7.         RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), transform.position, 20f);
    8.  
    9.         if (hit.collider != null && hit.collider.tag.Equals("Destroy"))
    10.  
    11.         {
    12.             if (hit.collider.tag.Equals("Destroy"))
    13.             {
    14.                 Debug.Log("Target Position: " + hit.collider.gameObject.transform.position);
    15.                 Debug.DrawLine(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
    16.                
    17.             }
    18.          
    19.  
    20.          
    21.  
    22.         }
    23.  
    24. }
     
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,550
    Juozukas likes this.
  3. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Your raycasting code doesn't look right. The parameters for a Raycast are Origin and Direction. You've provided different values. You're also drawing a line to the mouse position if the raycast hits something, which may be making you think it's working properly to begin with.

    You probably want to do something like this:
    Code (CSharp):
    1. void Raycasting() {
    2. {
    3.     Vector2 mouseDirection = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
    4.     Ray2D ray = new Ray2D(transform.position, mouseDirection);
    5.     RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 20f);
    6.  
    7.     if(hit.collider != null && hit.collider.CompareTag("Destroy"))
    8.     {
    9.         Debug.Log("Target Position: " + hit.transform.position);
    10.         Debug.DrawLine(ray.origin, hit.point);
    11.     }
    12. }
     
  4. Juozukas

    Juozukas

    Joined:
    Sep 2, 2017
    Posts:
    4
    Thanks for the input @Invertex, it was poorly written Raycast code by myself, thats why it didnt work the way I wanted.
    And of course big thanks @jeffreyschoch ! Worked like a charm !
     
    Invertex and LiterallyJeff like this.