Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

2D array: swapping texture of particular picked item


Recommended Posts

I'm having a brainfart. I've got a grid of 6x6 tiles. When the user clicks a tile, I want to turn it on (if it's off) and off (if it's on). 

While I can get the right tile picked and change the array value, I'm having trouble updating the image of the picked tile: instead, it always changes the last tile created.  How do I fix my pickMe function so that the correct tile changes image from off to on?


ar titles ={
	preload: function(){
		this.game.load.image('on', 'on.png');
		this.game.load.image('off', 'off.png');
create: function(){
	var cols = 6; //number of columns
	var rows = 6; //number of rows
    var tilesize = 45; //size of tile in px
	//game grid
  this.grid = [];

  var i,j;
  for(i = 0; i < rows; i++) {
	  //push in empty array

    for(j = 0; j < cols; j++) {
		//set initial value to zero
		this.addTile(i, j);

//creates the initial grid
	addTile: function(row, col){
		//position according to tile size
		var tileXPos = (col * 45) + (45/2);
		var tileYPos = (row * 45) + (45/2);
		//add image, set to off at start
		this.myTile = this.game.add.image(tileXPos, tileYPos, "off");
		//set anchor to centre
		this.myTile.inputEnabled = true;
		this.myTile.events.onInputDown.add(this.pickMe, this);
	pickMe: function(e){
		var pickedCol = Math.floor(e.x / 45);
		var pickedRow = Math.floor(e.y / 45);
		//this returns value of tile at pickedTile in grid
		this.pickedTile = this.grid[pickedRow][pickedCol];
		//if it's off, turn it on, and vice versa
		if(this.pickedTile === 0){
			this.grid[pickedRow][pickedCol] = 1;
			this.grid[pickedRow][pickedCol] = 0;




Link to comment
Share on other sites

38 minutes ago, samme said:

I think that's correct because the array members are arrays, not numbers.

Thanks, so..... how do I get the right index in order to change the texture of that particular tile?

Link to comment
Share on other sites

On 5/12/2018 at 12:20 PM, samme said:

Can you do it inside pickMe, with e?

That's what I'm trying to do. I'm not able to get the index of the tile. I can log out the column and the row, and get the value of the tile picked, but I'm not able to refer to the texture of the tile at the index.

Link to comment
Share on other sites

The picked tile texture key would be 


If you need to track all of them, you make store a second "grid":

  create: function () {
    // ...
    this.objGrid = [];

    var i, j;
    for (i = 0; i < rows; i++) {
      // ...

      for (j = 0; j < cols; j++) {
        // ...
        // ...

  addTile: function (row, col) {
    // ...
    this.objGrid[col][row] = this.myTile;


Link to comment
Share on other sites


  • Recently Browsing   0 members

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