- Home /
Any way to get collider2d bounds?
I am trying to limit an object's movement to the screen via something like this:
if (keepOnScreen) {
if (mouseLocation.x < screen.x ) {
mouseLocation.x = screen.x ;
}
else if (mouseLocation.x > screen.width) {
mouseLocation.x = screen.width;
}
if (mouseLocation.y < screen.y) {
mouseLocation.y = screen.y;
}
else if (mouseLocation.y > screen.height) {
mouseLocation.y = screen.height;
}
transform.position = mouseLocation;
}
This works, but of course the transform.position is the center of the object. I'd like to offset it by collision bounds. I can't set up an invisible wall, because I'm forcing the object position via the mouse and I really don't want to make the object move towards the mouse pointer using physics.
I'm not aware of any universal way to get the bounds of a Collider2D. It is possible (sometimes jumping through hoops), to get the bounds of specific colliders. I've answered a couple of questions about someone wanting a solution for a specific 2D collider. The answers were a bit involved. The code to find the bounds is far simpler if the object does not rotate.
Yes without rotation it is clearly simpler :) I suspect getting the bounds of a collider2d universally will have to be something created at an engine level... could be pretty slow otherwise if we're looking at points.
Thanks for your answers today, robertbu :)
Answer by SmooveB · Apr 12, 2014 at 07:22 PM
http://forum.unity3d.com/threads/211486-Physics2D-Bounds-and-Extents
But that will not work for complex shapes. For that, you could probably loop through PolygonCollider2D.points and record the extreme values for each direction.
Your answer