I’ve been experimenting with a Canvas for the first time and have a small game where obstacles randomly fly from the right to the left and the player on the left can move up and down to dodge them, score points for each dodge and it stores high scores.
I manually need to add obstacles to an array with a for loop to add them to a canvas at random x, y positions:
function ChooseRandom(min, max) { // random generator function
return Math.random() * (max - min) + min;
}
const obstacles = [ // array of obstacles to create using randomly generated positions
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
},
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
},
{
x: ChooseRandom(500, 2500),
y: ChooseRandom(0, 500),
width: 50,
height: 50
}
]
for (let i = 0; i < obstacles.length; i++) { // loop creating the obstacles using array
const obstacle = obstacles[i];
ctx.fillRect( // create obstacle
obstacle.x,
obstacle.y,
obstacle.width,
obstacle.height
);
}
The more items in the array the more difficult it becomes (as there’s more spawning in to avoid). Because each items uses the same code, is there a way to just type/set a number and it could populate the array with that many obstacle items in it?
Obviously this would save on code size but also I was thinking of adding a difficulty selection field, so if easy was selected it would only add maybe 6 obstacles on screen at any one time (6 items in the array), medium 12, hard 24 etc. So if there was away of populating the array with a number of duplicate items that can be generated from different set numbers, it would help in this situation.
2
Answers
I would do it like this:
You can set
n
to whatever number of obstacles you want to generate, create an emptyobstacles
array and populate the array by generating a new obstacle on each iteration of the loop. This does not prevent overlap though.You could use Factory function with configuration and some default values to generate your obstacles: