How to prevent player from moving outside the shape or area?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jjcdesamito

I’m already aware on how to create a wall using collision to prevent player from overlapping an object.

Now I wan’t is to prevent the player from moving outside the box or circle or any shape but I don’t know if this is possible. Or the only way to do this is create a “C” shape to act as a collider wall?

:bust_in_silhouette: Reply From: Dlean Jeans

Use a CollisionPolygon2D and set the Build Mode to Segments.

It’s easy to build a box shape inside the editor. But if you want a circle or any shape:

  • Create a Sprite with a texture of that shape (an image of a circle for example)
  • Press Sprite > Create CollisionPolygon2D Sibling

Images from Github

Hi, Thanks for replying!
I tried your suggestion but this does not prevent my player from going outside the polygon I created. Do I also need to attach some scripts?
I want my player movement to be contained only inside the polygon like trapping him inside an invisible bubble.

jjcdesamito | 2019-06-11 10:32

No scripts needed. I think you might have the wrong settings. Do a double check.

Dlean Jeans | 2019-06-11 10:42

Proof that it works:

Proof

Dlean Jeans | 2019-06-11 10:50

Thanks for the pic.
I didn’t know I should use StaticBody2D. (I tried using Node2D as parent)
It works now as expected.
Thank you!

jjcdesamito | 2019-06-11 11:16

This works like a charm, I also found that going into the generated PoolVector2Array under the Polygon type one can easily edit the coordinates to make pixel perfect rectangular bounds.

There might be an easier way to create a perfect rectangle and segment it but this approach worked well and took all of 5 minutes to create two separate zones to be used to separate different pong paddles.

BenVella | 2020-09-26 19:37