# Unity: Restrict movement inside a gameobject (2D)

I've been sort of trying my own thing but it's super buggy so I'd like to see what other people have done to create moveable spaces. In essence, I just want to restrict my character's movement to inside of a sprite. So one of my sprites is the character and another one of my sprites is a box -- I want to make it so my character can't leave the box. I've been modifying transform.position on mouse click in order to move my character, but now I'm not sure if this was the smartest idea.

• Is your containing object always a box (ie. a rectangle) or do you want to support other shapes based on 2D colliders (circle, polygon), or based on the pixel opacity values in the sprite? – DMGregory Jun 3 '15 at 21:48
• One of the problems with my first solution was that it only worked for rectangles -- I want it to work for any shape of the sprite – Jeff Burghess Jun 3 '15 at 22:55
• The thing about sprites is that they are inherently rectangular--they are literally a Rect on a Texture2D. You're going to have to analyze your sprite for opacity, like DMGreg mentioned. Check each pixel, if it has alpha of less than 255, create a 1-pixel large collider. This will have performance issues with high-res maps. We'd probably need more context on why you need this method to suggest other avenues of action. – ketura Oct 4 '15 at 4:26

If you're moving the transform relative to the wrapping parent, you could always Mathf.Clamp(high,low) your coordinates.

If not a box, I think you need to defer movement to physics engine for desired functionality.

• Got an idea on how to do the latter? I sort of want something like the inverse of a polygon collider 2d, if that makes sense. – Jeff Burghess Jun 7 '15 at 3:11

2 ideas came to my mind. Look at illustrations:

First option is obvious, add colliders to boundaries of your game area.

The second option is, to limit your characters movement inside boundaries within your script.

For example, if you have a code that controls the position of character, check if your values falls inside the boundaries of your game area, then clamp it to max and min values if it exceeds.

Thankfully, unity has this feature built-in in Mathf library with "Mathf.Clamp" function. So in this example you need to check like this:

var finalVertical = Mathf.Clamp (rawVertical, -c, +c);
var finalHorizontal = Mathf.Clamp (rawHorizontal, -a, +b);


• Instead of having four (or six in a 3d game) colliders as barriers around your play area and reacting on OnTriggerEnter, you can alternatively have one collider representing the game area and react on OnTriggerLeave. This has the advantage that you don't need to worry about having the outer colliders too small so an object with an extremely high speed can clip out of them. – Philipp Dec 4 '15 at 18:40