user3292309
user3292309

Reputation: 45

Looping sprite addition in Phaser inside AJAX function

I have the following code in a game I am making using Phaser:

game.add.sprite(response.Turret0.posx, response.Turret0.posy, "turret");
game.add.sprite(response.Turret1.posx, response.Turret1.posy, "turret");
game.add.sprite(response.Turret2.posx, response.Turret2.posy, "turret");

I wanted to use a loop to run the statements above. However, the following approach doesn't seem to work:

for(int i=0;i<length;i++)
    game.add.sprite(response.'Turret+i'.posx, response.Turret0.posy, "turret");

The code is in an AJAX function hence I have to stay in the function bounds. Why is this not working, and how can I fix it?

Upvotes: 1

Views: 346

Answers (2)

MikaelE
MikaelE

Reputation: 95

With your current naming standard I think using:

response['Turret'+i]

should work, but I agree that declaring Turret as an array from the start as the previous answer suggested would be a better approach.

Upvotes: 1

Kraylog
Kraylog

Reputation: 7553

The problem is really with naming variables with consecutive IDs (Turret0, Turret1, etc.). This transforms structural information into naming convention, which is of course less convenient to use.

Instead, you should return an array of Turrets in your AJAX response, and access it through turrets[i] in the loop.

Upvotes: 1

Related Questions