Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top