Constrain a sprite within a polygon area in Phaser

1.2k views Asked by At

I am creating a click and point adventure game. I have a character walking in the area but I'm unsure as to how to constrain where his feet can venture to. In the attached image, I have his feet in yellow, but I must not allow him to go outside the blue polygon area on the floor.

Any ideas on how to make this work? Please bear in mind, I'm creating a tween for the character to follow when the user clicks the screen. If he bumps into an area outside of the polygon, it will make the player (pink rectangle) stop.

I've tried arcade physics but that's only for square based sprites. I guess I have to use p2 physics? Can I use p2 physics on shapes or maybe a simple line like the polygon area?

enter image description here

1

There are 1 answers

0
PhotonStorm On BEST ANSWER

You don't need to use any of Phasers physics engines to handle this, you can do it using the Polygon geometry object and just check if the click is within the polygon or not.

Here's an online example: http://phaser.io/examples/v2/geometry/polygon-contains

But the code is quite simple. First create a polygon (be aware about overlapping points and the way the poly winds, see docs for details):

    poly = new Phaser.Polygon([ new Phaser.Point(200, 100), new Phaser.Point(350, 100), new Phaser.Point(375, 200), new Phaser.Point(150, 200) ]);

and then just check if they've clicked within it:

if (poly.contains(game.input.x, game.input.y))
{
    // allow walk
}