- Home /
2D Raycast in any direction
I'm sure there's answer for this somewhere but I can't for the life of me find one.
I'm attempting to cast a 2D Raycast/Linecast from my player in the direction of my mouse, A straight line from my character that heads toward my mouse and continues on in that direction until a certain distance has been surpassed.
A C# solution would be most appreciated
Answer by NerdRageStudios · Jun 07, 2017 at 03:32 AM
This should work
RaycastHit2D hit = Physics2D.Linecast(transform.position, Input.mousePosition, distance);
That will return the first object hit.
If you want all objects, simply return an array
RaycastHit2D[] hits = Physics2D.LinecastAll(transform.position, Input.mousePosition, distance);
simply replace distance for whatever you want.
If you want it to travel in the direction, simply get the direction using a vector, then use a raycast in that direction.
Vector3 direction = (transform.position - Input.mousePosition).normalized;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, distance);
Hey, thanks for the quick reply! Can't believe I didn't see this in docs (Doi!) This is exactly what I needed. I've accepted your answer and even threw you a few points :)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Mouse pos + raycast 1 Answer
Finding Distance between Angles and Points 2 Answers
How to make a ball stay in the air longer when force is added? 1 Answer
Working with RayCast 1 Answer