# Draw line around objects

## Recommended Posts

Hi all,

I'm new to Phaser. But I would like to know, if we can make a game with this goal:

user draw line around objects, and when mouse up, the objects disappear. The line should be close the gap to take effect.

##### Share on other sites

Yes, but you'll have to figure out a way to draw the line (I imagine the Graphics object would be your best bet here) ensuring the resultant polygon is smoothed and simplified as they draw, then a way to determine objects inside the polygon the user creates.

##### Share on other sites

I can think of a few ways to accomplish this --

Assume the drawn shape is defined by points P[1], P[2], P[3], etc., all connected by a series of lines.  Then you can:

1) Use the non-zero winding rule.

https://en.wikipedia.org/wiki/Nonzero-rule

2) Use the even-odd rule.

https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule

3) Create a temporary canvas, use the points to draw and fill a shape, then check the mapping between the stars in the temporary canvas to see what colors the resulting pixels are.

To capture the points:

• Have a state variable that can be IDLE, DRAWING, or CLOSED.
• On the first mouse down, go from IDLE to DRAWING. Record the first point.
• Every update while DRAWING, record a new point on the drawing area if the new point is more than d distance from the last point.  You would need to experiment to get a good number for d.  If d is too small then you risk running out of memory for the points.  Memory for the points could be dynamically allocated or pre-allocated in a constant-size array.
• On mouse up, go from DRAWING to CLOSED.
• On CLOSED, calculate what stars are in and out of the drawn polygon.  Change to IDLE.

On every frame draw, draw the lines defined by the point array.  Grab the Context from the Canvas Phaser is drawing on and use moveTo(), lineTo(), and stroke() to draw the unfinished polygon.

Once you can the basic mechanics implemented, then you can move on to optimization and polish.

Tom