Jump to content

variable updating when it shouldn't


Kobaltic
 Share

Recommended Posts

I have a variable of holdSquare I set it to the object square. It updates after I change the values for square.x and square.y but it shouldn't change.

function move(square){   var length = 16;    var holdSquare = square;     if (checkOverlap(square, number[length])){            alert(holdSquare.x);        square.x = number[length].x;        square.y = number[length].y;            alert(holdSquare.x);             number[length].x = holdSquare.x;       number[length].y = holdSquare.y;         }    }

If you look at the first alert the value is correct at 250 for both x and y. At the second alert it changes to 325 for both x and y. number[length].x and .y are both 325. It seems as if holdSquare picks up this value and it shouldn't. My ultimate goal is to have square and number[length] trade values. Any thoughts as to what is going on?

Link to comment
Share on other sites

holdSquare and square are referencing the same object. Change one, you change the other, because they are the same thing.

You'll need to use temp X and Y variables separate to the square object.

var x = square.x;var y = square.y;//or var temp = new Phaser.Point(square.x, square.y);
Link to comment
Share on other sites

For the record, all objects (including arrays) are always referenced, whereas simple types (such as numbers and strings) are not. This leads to some unusual situations regarding equality, such as the following:

// Below are comparisons of various objects using non-strict (==) equality// which you would expect to work in such situations as these. As you can see// even if objects have the exact same properties, they do not match equality.({x: 1, y: 1} == {x: 1, y: 1});false// Same goes for arrays, even empty ones[] == [];false// And built-in objectsnew Date() == new Date();false// However simple types (numbers, booleans, strings etc) are fine"abc" == "abc";true1 == 1;true

If you want to copy a Phaser.Point object it has a handy clone method:

var holdSquare = square.clone();
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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