ScratchEnjoyer
ScratchEnjoyer

Reputation: 3

How can I make it so that my Raycast2D references every object that it hits?

I want to write code that will cast a ray from my player, and for every enemy that the ray touches I want to be able to reference that enemy, to do things such as finding the furthest enemy or calling methods inside of the enemy. Currently inside of my Player object I have the following code:

Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 castPointPos = new Vector2(castPoint.position.x, castPoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(castPointPos, mousePos-castPointPos, 5, whatToHit);

Debug.DrawLine(castPointPos, mousePos, Color.green);
if (hit.collider != null)
{
        Debug.DrawLine(castPointPos, hit.point, Color.red);
        Debug.Log("I'm hitting " + hit.collider.name);
}

This works perfectly fine, but I can only use this to reference the first object the ray touches. How do I make an array that stores each object after that?

Upvotes: 0

Views: 209

Answers (1)

Charly
Charly

Reputation: 470

You could use Physics2D.RaycastAllor RaycastNonAlloc if you're worried about performance.

Vector2 origin; //init this variable
Vector2 direction; //init this variable

RaycastHit2D[] = Physics2D.RaycastAll(origin, direction);

link to docs

(Be aware that array that you get back is not sorted by distance so you'll have to manage that yourself.)

Upvotes: 1

Related Questions