function setup()
{
createCanvas(800, 600);
//other code has been omitted
}
function generateRandomBalls() {
var numRows = 5; // we have 4 rows, 5 including the top row
var radius = 8;
var startX = Math.random();
var startY = Math.random();
for (var row = 0; row < numRows; row++) {
for (var i = 0; i <= row; i++) {
var xOffset = row * (sqrt(3) * radius);
var yOffset = row * (radius * 3) / 2;
var x = startX + xOffset;
var y = startY - i * (radius * 3) + yOffset;
var ball = Bodies.circle(x, y, 11, {
restitution: 1,
friction: 0.5,
render: { fillStyle: 'red' }, // we set the color of the ball to red
velocity: { x: 1, y: 2 },
//collisionFilter: { group: 0x0002 }
});
Body.setAngle(ball, PI / 2); // we change the angle from -PI/2 to PI/2 to flip the triangle
balls.push(ball);
}
}
World.add(engine.world, balls);
}
The code should make the positions of the red balls are within the canvas at random but always remain with a grid-style (triangle style) shape, so that every time the game starts, it start at a random position of the canvas.