Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

Array of x and y positions


Marcus
 Share

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];
    }

 

Link to comment
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[0]; 

strawberry.y = randPos[1]];

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.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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