0

I'm trying to make a hover for every tile, but when I use tileArray[i].x it uses the last tiles position. And I'm trying to get the position of the tile I'm hovering.

Here is the code I've made.

for (x = 0; x < mapxtiles; x++) {
    for (y = 0; y < mapytiles; y++) {
        if(map[x][y].height != 'x') {
            i++;
            var topPos = (x * 16) + (y * 16) - 24;
            var leftPos = (y * 32) - (x * 32) + (mapxtiles * 32) - 32;


            var normalTileTexture = PIXI.Texture.fromImage("./assets/map/normal.png");
            var tileHoverTexture = PIXI.Texture.fromImage("./assets/map/hoverTexture.png");

            tileArray[i] = new PIXI.Sprite(normalTileTexture);

            tileArray[i].setInteractive(true);

            var tileHover = new PIXI.Sprite(tileHoverTexture);

            tileArray[i].mouseover = function(mouseData) {
                tileHover.position = new PIXI.Point(tileArray[i].x - 2, tileArray[i].y + 22);
                floorMap.addChild(tileHover);
            };

            tileArray[i].position = new PIXI.Point(leftPos, topPos);
            floorMap.addChild(tileArray[i]);
        }
    }
}
Joery
  • 759
  • 4
  • 13
  • 33

1 Answers1

1

i is a counter which has reached a certain value at the end of your loop. if you hover your tile, it will always have the last value. a workaround for that, is to wrap your code in a closure:

 (function (a) {
   tileArray[a].mouseover = function(mouseData) {
     tileHover.position = new PIXI.Point(tileArray[a].x - 2, tileArray[a].y + 22);
     floorMap.addChild(tileHover);
   };
 })(i); 

what i do here:

i wrap your event-handler in an iife with i as parameter and recieve it as a inside the closure. this is for illustration purposes, you could of course leave the inner var by the name of i

it is also a little bit more readable, to just move it into a function which is declared outside of your loop:

 function helperfunction (tileArrayElement, tileHover, floorMap) {
   tileArrayElement.mouseover = function(mouseData) {
     tileHover.position = new PIXI.Point(tileArrayElement.x - 2, tileArrayElement.y + 22);
     floorMap.addChild(tileHover);
   };
 }

and call it in your loop:

for (x = 0; x < mapxtiles; x++) {
    for (y = 0; y < mapytiles; y++) {
        if(map[x][y].height != 'x') {
            // your other code...

            helperfunction(tileArray[i], tileHover, floorMap);

            // your other code...
        }
    }
}
hereandnow78
  • 14,094
  • 8
  • 42
  • 48