Jump to content

Best way to create a grid system in Phaser?


phaserdev
 Share

Recommended Posts

Let's say I create a grid system in Phaser of rows and columns, and want to populate various cells in that grid with different elements.  I want to be able to drag elements from one cell to another, and track their movement from cell to cell in some data structure.  I'm new to Phaser, and more used to low-level canvas API drawing.  How can I track movement from cell to cell?  Should I add elements with game.add.sprite?  Can sprites hold row/column locations?

Link to comment
Share on other sites

I can't offer you a solution, but is there a specific reason to use Phaser for this? This is something that would be much simpler to create in the DOM :)

If you really want to do this in Phaser you'd probably need a sprite or image per cell, enable arcade bodies and drag on the elements (check the drag examples). Then you could add the elements as children to the cell objects (addChild) depending on the closest cell when releasing the mouse (also a callback in phaser)and update your data. Maybe the arcade physics overlap function is useful for keeping track of this,.

I'd give you a more clear example and some links but I'm currently on my phone :) if you need some more info/help just let me know, I'll be able to reply more thoroughly in an hour or so

Link to comment
Share on other sites

I would not use physics for this at all, but instead manage the math yourself.

 

You can add whatever properties you want to a Sprite instance but try not to override the existing ones. You could do something like this:

Object.defineProperty(sprite, 'cellX', {  get: function() {    return Math.floor(this.x / CELL_WIDTH);  }.bind(this)}

That will create a read-only property on the sprite called "cellX" that will return its x position in a grid as a function of its x position (if that sentence makes any sense at all). That's just one possibility.

 

I would make an object out there that knows where all the sprites are and, as you drag them around, gets told what sprites are swapping and kicks off tweens or whatever to swap them in a pretty way.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...