Working with arrays of points, and polygons in phaser
When working with on the fly graphics in phaser, there might come a time in which i might want to do something with a collection of points that form a shape, or drawing, or polygon. In this post I will be writing about how to make on the fly shapes without using any external assets in phaser using graphics display objects.
1 - What to know
1.1 - This is a phaser ce 2.x post
2 - A Graphics.drawPolygon example
I often start a post off with a simple example of what I will be writing about in more detail in post. As such here is a quick, simple example of use for Graphics.drawPolygon in phaser.
Here I just made a very bad drawing of an arrow, but you should get the basic idea. You need create a Graphics Display Object, set a style for it, and then pass an array of points to it that follow the simple formula of:
3 - Arrays of points
Well regardless of how you might think with this in phaser just a single linear array is used, so whenever you want to feed some points to a method like Graphics.drawPolygon this is the format the array of points should be in.
4 - Generating a points array
So when it comes to making a shape in phaser I want to think in terms of of an array of numbers that are the x, and y values of each point.
5 - Add Phaser Graphics display Object
Once I have an array of points to pass to the polygon method, the next step is the add method of the main game object that is used to create a new graphics display object via game.add.graphics(x,y). This is what I call first in my create method to get a new graphics display object that will contain the drawPolygon method, along with a bunch of other useful stuff.
6 - Setting Graphics line Style in phaser
Another important method to know of is the graphics lineStyle method, this is what to use to style lines that are used to draw polygons, and anything else in the graphic that involves drawing a line. This is a method in which I pass lineWidth, color, and alpha too in order to set line style.
this sets a lineWidth of 3, a lineColor of green, and an lineAlpha (or transparent) value of .8. Of course Alternatively I can directly set those values by setting each property independently as well.
Looking at the source code is may be generally better to use the lineStyle method as it also runs some checks on the currentPath
7 - Conclusion
I hope this post has helped you gain a better understanding of how to work with polyGons in phaser. If you liked this post you might want to check out my many other posts on phaser. Because this post is not graphics my post on Graphics in general in phaser might be of specific interest. I have also wrote posts on making sprite sheets with canvas), which can also be used as a way to make graphics in phaser without an external sprite sheet as well.
In any case have fun working (or playing), with phaser.