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): Void Raycasting(){ { RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), transform.position, 20f); if (hit.collider != null && hit.collider.tag.Equals("Destroy")) { if (hit.collider.tag.Equals("Destroy")) { Debug.Log("Target Position: " + hit.collider.gameObject.transform.position); Debug.DrawLine(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition)); } } }
What you're describing is already the default behaviour of raycast, it returns the first hit it finds. You can also use RaycastAll to get all collisions along the ray length. https://docs.unity3d.com/ScriptReference/Physics2D.RaycastAll.html But for your purposes that shouldn't be needed.
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): void Raycasting() { { Vector2 mouseDirection = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position); Ray2D ray = new Ray2D(transform.position, mouseDirection); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 20f); if(hit.collider != null && hit.collider.CompareTag("Destroy")) { Debug.Log("Target Position: " + hit.transform.position); Debug.DrawLine(ray.origin, hit.point); } }
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 !