# Array of x and y positions

## Recommended Posts

So I want to make an array list containing specific x and y positions of a sprite. I know what I've got now isn't right, but I can't find how to do it in a way I understand

``````var positions1 = [{x: 100, y:60}, {x: 300, y:60}, {x: 500, y:60}];

if (Phaser.Geom.Intersects.RectangleToRectangle(player.getBounds(), strawberry.getBounds())) {
let randNum = Math.floor(Math.random() * 3)
strawberry.x = positions1.x[randNum];
strawberry.y = positions1.y[randNum];
}``````

##### Share on other sites

Currently, you're trying to access arrays that do not exist. Using positions1.x[randNum], you are trying to find an property of positions1 that does not exist (x). Your current code would work if

``````var positions1 = {

x: [100, 300, 500],

y: [60, 60, 60]

}``````

The way in which I would do this would be to set positions1 equal to [[100, 60], [300, 60], [500, 60]] (var positions1 = [[100, 60], [300, 60], [500, 60]];) to use nested arrays. Then, you could access a random set of coordinates with

``let randPos = positions1[Math.floor(Math.random() * 3)];``

and set the coordinates of the sprite to the respective x and y values with

``````strawberry.x = randPos;

strawberry.y = randPos];﻿``````

What this does is set randPos equal to one of the nested arrays in the positions1 array, giving it a value of [100, 60], [300, 60], or [500, 60]. Then you can access the first or second element said array.