I want to restrict object movement inside an area. My object follows cursor position.

I have already done that for the area border using Mathf.Champ to the translate because the borders are square shaped (got the idea from Unity: Restrict movement inside a gameobject (2D)). The thing is that inside the box area there can also be other shapes (colliders) which I don't want my object to go over.

I know people suggest using physic collisions, but my game needs a unit perfect positions so I can't use physics due to physics' default contact offset (the one physics use to detect collisions).

Here is a short video of what I have:


As you can see, movement is restricted (clamped) inside the box area but I want the movement to also be restricted to not go over the black area.

Is there a way to be able to do this with just clamping or do I need a raycast system or something like that?

  • 1
    \$\begingroup\$ The contact offset doesn't seem like it should be a deal-breaker here. You can scale down your colliders or offset your queries to compensate, and round the outcomes to "unit perfect positions" wherever you need. \$\endgroup\$ – DMGregory Dec 5 '18 at 9:48

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.