Jump to content

Arcade object's x & y keep increasing


Recommended Posts



I'm working on storing the locations of objects in a JSON file, and then place objects in the create function. But I'm noticing a weird bug. The JSON looks like this:

{    "bigRocks":[      {"x":"420", "y":"200"},      {"x":"699", "y":"1350"}    ],    "treeLogs":[      {"x":"250", "y":"500"},      {"x":"856", "y":"400"}    ],    "hunters":[      {"x":"50", "y":"140"},      {"x":"1150", "y":"2885"}    ]  }

I load in this JSON like this:

game.load.text('locations', 'assets/locations.json');

in preload and then I use this in create:

game.cache._text.locations.data = JSON.parse(game.cache.getText('locations'));

and for creating objects:

//Enemy hunters  hunters = game.add.group();  hunters.enableBody = true;  hunters.physicsBodyType = Phaser.Physics.ARCADE;  var hunterLocations = game.cache.getText('locations').hunters;  objectQuantity = Object.keys(hunterLocations).length;  hunters.createMultiple(objectQuantity, 'zookeeper');  var i = 0;  hunters.forEach(function(item){    item.reset(hunterLocations[i]['x'], hunterLocations[i]['y']);    item.body.static = true;    i++;  });

I'm using the same method for P2 physics objects, but when I do this for arcade physics objects I notice something weird;

when I console.log the hunterLocations or item.x or item.y in the function above the positions are right. But when I console.log them in the update function like this:

hunters.forEach(function(item){  console.log("hunter x: "+ item.x);  console.log("hunter y: "+ item.y);});

every update a 0 is added to the item.x and item.y. So it starts at 1150,800, then 11500,8000, then 115000,80000 etc.


I've tried lots of things including storing the x and y in a variable first before using item.reset but all with the same result. The only time it works is when I just use numbers or variables defined in the game file.


I'm really lost and thinking this is a bug, but I'm not sure. Help would be appreciated!




Link to comment
Share on other sites

It's because the data types are strings and this is JavaScript working its wonderful weird magic when adding numbers to strings. Try this:

var x = parseInt(hunterLocations[i]['x'], 10);var y = parseInt(hunterLocations[i]['y'], 10);item.reset(x, y);
Link to comment
Share on other sites


  • Recently Browsing   0 members

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