[Example]Javascript/HTML5: Store game object in variable

For now, you need to program in javascript to store a game object in a variable.

Thus, you need not look for the object in each frame.

This can be useful for displaying information of a selected object, or to mark a moving object game, that does not hold the position.

First, we must create the variables in the document, which will store the game object:

[code]//Create variable to store game object
var js = “var selected = null;” // put your JS code here

var oScript = document.createElement(“script”);
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);[/code]

Then, using a single search, we assign the selected game object.

We can use a object variable ‘id’, the Z order, or the position of the object. I used the position of the object to locate a specific game object.

But first, we must store the search data in a variable of the scene to access it from javascript.

I have stored the position of the game object in the scene variables ‘positionX’ and ‘position Y’.

The ‘objects’ variable is created by GDevelop and stores the list of game objects I need.

[code]if(objects)
{
var container = runtimeScene.getVariables();
var positionX = container.get(“positionX”).getAsNumber();
var positionY = container.get(“positionY”).getAsNumber();
for (var i = 0; i < objects.length; i++)
{
if((positionX==objects[i].getX()) && (positionY==objects[i].getY()))
{
selected = objects[i];
}

}

}[/code]

After, to use the stored game object, I do the opposite direction, that is, pass the values I need to variables of the scene.

For example, I need the position:

if(selected) { var container = runtimeScene.getVariables(); container.get("selectedX").setNumber(selected.getX()); container.get("selectedY").setNumber(selected.getY()); }

I stored position in scene variables ‘selectedX’ and ‘selectedY’.

Download link: http://www.speedyshare.com/z8CAq/PointerToObject.zip