Jump to content

mouse events for hex tiles


MonsieurBlutbad
 Share

Recommended Posts

Hello,

I am new to phaser and I want to make a hex grid. I use sprites for my hex tiles. Now I want to bind some mouse events to those sprites. The problem is that the sprite is rectangular in shape and the event is also triggered on the transparent areas of my sprite. So there is some overlapping and inaccuracy for my events.

Basically I want to have a non-rectangular hitbox for my sprite events. Can I somehow use the transparency of my sprite or at least draw some kind of shape to achieve this? I am not using any physics engine yet and I am not sure if I need to. 

 

hexagonGroup = game.add.group();
for (var tileY = 0; tileY < gridSizeY; tileY ++) {
   for (var tileX = 0; tileX < gridSizeX; tileX ++) {
      var worldCoordinates = getWorldCoordinates(tileX, tileY);
      var hexagon = game.add.sprite(worldCoordinates.x, worldCoordinates.y, 'hex');
      hexagon.inputEnabled = true;
      hexagon.events.onInputDown.add(hexClicked, this);
      hexagonGroup.add(hexagon);
   }
}

 

Link to comment
Share on other sites

you can set the area to be used for input detection with the hitArea method, the hit area can be set using a shape primative.  Setting the hit area is faster than using pixel transparency for detection.  For a hexagon you could simplify the hit area to be a circle (fast detection calculation) or go the whole hog and define a polygon (slower detection calculation)

eg. for a circle detection area, try something like this where you create each hex

hexagon.hitArea = new Phaser.Circle(hexagon.width/2, hexagon.height/2,hexagon.width);

Link to comment
Share on other sites

In case anybody is interested, this is how I got it working. I know the Math on the Polygon is a bit verbose, but I kept it like this for clarity for now.

hexagonGroup = game.add.group();

for (var tileY = 0; tileY < gridSizeY; tileY ++) {

  for (var tileX = 0; tileX < gridSizeX; tileX ++) {
  
    var world = this.getWorldCoordinates(tileX, tileY);

    var hexagon = game.add.sprite(world.x, world.y, 'hex');
                
    var points = [];
                
    for (var i = 0; i < 6; i++) {
      points = {
        x: (hexagon.width/2) + (hexagon.width / 2) * Math.sin(2*Math.PI/6*i + (2*Math.PI/12)),
        y: (hexagon.height/2) + (hexagon.width / 2) * Math.cos(2*Math.PI/6*i + (2*Math.PI/12))
      };
    }
                
    hexagon.hitArea = new Phaser.Polygon(points);

    hexagon.inputEnabled = true;
                
    hexagon.events.onInputDown.add(this.hexClicked, this);
                
    hexagon.events.onInputOver.add(this.hexHovered, this);

    hexagonGroup.add(hexagon);

  }
}

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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