Visualise Physics2D.BoxCastAll
I am working on a 2D game and I just implemented an attack function using Physics2D.BoxCastAll. However I am having a hard time to get the attack hit-box the size I want it to be, since I can't see the box. Is there a way to visualize the box I am casting ? Is Physics2D.BoxCastAll better than turning a collider on and off for an attack function?
Answer by streeetwalker · Mar 22, 2020 at 10:16 AM
@LucasVaz . Physics2D.BoxCastAll returns a RayCastHit2D array. The hit point of each element of that array is the element.point.
Get that point and use it as the center to draw a box. so for example in pseudo code
Vector2 upperLeft = new Vector2( -boxSize.x/2, boxSize.y/2 );
Vector2 upperRight = new Vector2( boxSize.x/2, boxSize.y/2 );
Vector2 lowerLeft = new Vector2( -boxSize.x/2, -boxSize.y/2 );
Vector2 lowerRight = new Vector2( boxSize.x/2, -boxSize.y/2 );
RayCastHit2D[] objectsHit = Physics2D.BoxCastAll ( ...., boxSize, ... );
for each( RaycastHit2D hitObj in objectsHit ){
vector2d hitPoint = hitObj.point;
// draw the box here using hit point as the center and boxSize.x and boxSize.y
Debug.DrawLine( upperLeft +hitPoint, upperRight +hitPoint );
Debug.DrawLine( lowerLeft +hitPoint, lowerRight +hitPoint );
--- you get the idea? continue to draw the other two sides...
}
That should show you the box at each object hit - not tested so my code may need syntax fixes and what not.
Your answer
Follow this Question
Related Questions
How do you make one game object follow the shape of another game object? 0 Answers
Find all locations where a ray/ raycast insects an object 0 Answers
Raycast Not Detecting Hit 0 Answers
Create a custom polygon collider based on overlapping ogjects 0 Answers
Hi guys, I need help with C# Scripting using Raycast. 1 Answer