# Box selection with Physics2D.BoxCastAll is mirrored when selecting in the bottom half of the screen

Using Physics2D.BoxCastAll based on rectangle is working fine when drawing is started on the top part of the screen, but when drawing is started on the bottom you can see this strange mirroring effect.

Code:

void OnGUI()
{
// LMB clicked
if (Input.GetMouseButtonDown(0))
{
boxStartPosition = new Vector2(
Input.mousePosition.x,
Screen.height - Input.mousePosition.y
);
}

// LMB drag
if (Input.GetMouseButton(0))
{
boxEndPosition = new Vector2(
Input.mousePosition.x,
Screen.height - Input.mousePosition.y
);

rectangle = new Rect(
boxStartPosition.x,
boxStartPosition.y,
boxEndPosition.x - boxStartPosition.x,
boxEndPosition.y - boxStartPosition.y
);

GUI.DrawTexture(rectangle, RectangleTexture);

float pixelsToWorld = Camera.main.orthographicSize / (Screen.height / 2f);

Vector2 boxCenter = Camera.main.ScreenToWorldPoint(rectangle.center);

boxCenter.y = Mathf.Abs(boxCenter.y);

float boxWidth = Mathf.Abs(rectangle.size.x) * pixelsToWorld;
float boxHeight = Mathf.Abs(rectangle.size.y) * pixelsToWorld;
Vector2 boxSize = new Vector2(boxWidth, boxHeight);

BoxCastDebug.DrawBoxCast2D(boxCenter, boxSize, 0f, Vector2.zero, 0f, Color.black);
hits = Physics2D.BoxCastAll(boxCenter, boxSize, 0f, Vector2.zero, 0f);
}
}



Can anyone help me to solve these issues? Is it directly connected with setup of my scene, camera or scripts?

I'll start off by mentioning that I'm not an expert with Unity, but looking at the image provided and your code, here what I think the issue is.

The behaviour we see is this: when you click/drag from top left of the rectangle, you get a rectangle "outline" and a "filled" paler rectangle following the mouse positions, when you click/drag from the bottom right of the rectangle, you get the "filled" paler rectangle following the mouse position, while the "outline" is mirrored vertically.

The code you supply suggests that you draw two rectangles:

• GUI.DrawTexture(rectangle, RectangleTexture);
• BoxCastDebug.DrawBoxCast2D(boxCenter, boxSize, 0f, Vector2.zero, 0f, Color.black);

The main difference here is that essentially, you don't supply the same parameters for drawing both rectangles because you change the absolute value of the "box center" (boxCenter.y = Mathf.Abs(boxCenter.y);).

Assuming the Camera.main.ScreenToWorldPoint() has its center in the center of the screen, then boxCenter.y will always end up being in the top part of of the screen, thus making your call to BoxCastDebug.DrawBoxCast2D() always draw its rectangle in the upper half part of the screen.

How to fix this? Well it depends on what was your intention with making the y position positive only, but perhaps not doing so would fix the issue.