- Home /
The question is answered, right answer was accepted
2d Raycasting on rotating rectangle.
I was doing my collisions via Raycasting from a collider horizontally and vertically base on collider bounds, problem is when rotating the collider, I want the rays to be perpendicular on the collider rectangle itself not on its bounds. Any idea how to do it properly?
Answer by dhon2407 · Jun 29, 2018 at 01:52 AM
More details:
I was following tutorials from youtube by Sebastian Lague on collisions via Raycasting. I just want to add some rotation to the box collider (like swinging weapon). I'm missing some math formula and having hard time figuring it out(not good at Trigo). Anyways here are some excerpts from code. I've added also some picture for visual reference. I know this will be easy for someone but can find the specific formula. :)
public void UpdateRaycastOrigins()
{
Bounds bounds = collider2d.bounds;
bounds.Expand(skinWidth * -2);
raycastOrigins.bottomleft = new Vector2(bounds.min.x, bounds.min.y);
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
raycastOrigins.topleft = new Vector2(bounds.min.x, bounds.max.y);
raycastOrigins.topright = new Vector2(bounds.max.x, bounds.max.y);
}
void CalculateRaySpacing()
{
Bounds bounds = collider2d.bounds;
bounds.Expand(skinWidth * -2);
float boundsWidth = bounds.size.x;
float boundsHeight = bounds.size.y;
horizontalRayCount = Mathf.RoundToInt(boundsHeight / dstBetweenRays);
verticalRayCount = Mathf.RoundToInt(boundsWidth / dstBetweenRays);
horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1);
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);
}
Answer to this can be found here.
This lines of code will to the trick:
BoxCollider2D collider = (BoxCollider2D) this.gameObject.GetComponent<Collider2D>();
float top = collider.offset.y + (collider.size.y / 2f);
float btm = collider.offset.y - (collider.size.y / 2f);
float left = collider.offset.x - (collider.size.x / 2f);
float right = collider.offset.x + (collider.size.x /2f);
Vector3 topLeft = transform.TransformPoint (new Vector3( left, top, 0f));
Vector3 topRight = transform.TransformPoint (new Vector3( right, top, 0f));
Vector3 btmLeft = transform.TransformPoint (new Vector3( left, btm, 0f));
Vector3 btmRight = transform.TransformPoint (new Vector3( right, btm, 0f));