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, Vector3.one);
     Gizmos.DrawWireCube(Vector2.zero, Box.size);

 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: http://imgur.com/a/mjgXE

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?


Try using Box.center instead of Box.position. From the docs for Rect.position:

This is the same as min, except that setting it will move the rectangle rather than resize it.

Both Physics2D.BoxCastAll and Gizmos.DrawWireCube expect you to provide a center point and a size. Right now, your box-cast is being centered at the minimum of the rectangle. If you use Box.center instead, then your gizmos should show the correct rectangle and your box cast should match it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.