Visualize BoxCast Rect

Im trying to find a way to visualize, and Edit the Physics2D.BoxCast from the Editor.

I wrote the methods below to visualize the BoxCast, and edit in the editor:

    public Rect Box;
    private void OnDrawGizmos()
        Gizmos.color = Color.magenta;
        Gizmos.matrix = Matrix4x4.TRS(transform.position + (Vector3) Box.position, transform.rotation,;
        Gizmos.DrawWireCube(, Box.size);

    // Update is called once per frame
    private void Update()
        var hits = Physics2D.BoxCastAll(transform.position + (Vector3) Box.position, Box.size,
            transform.eulerAngles.z, Vector2.right, 0, 1 << LayerMask.NameToLayer("Player"));

        foreach (var hit in hits)

It works fine, but when I edit the object rotation I get this problem:

I can fix it easily, putting just transform.position, instead of transform.position + (Vector3)Box.Position.
But if I do it, i will not be able to edit the Raycast position.

So, how I can solve this?

Make sure that you only use the z-axis for drawing the cube and you shouldn’t sum the position of the object with the raw position of the box. What you want is a forward direction towards the object. You can achieve this by using the TransformDirection method of the Transform class:

var fw = transform.TransformDirection(Box.position);

And now you can safely sum the vectors:

Gizmos.matrix = Matrix4x4.TRS(transform.position + fw, transform.rotation,;

You need to do this with the raycast as well.