xxxxxxxxxx
91
const { Engine, World, Bodies, Body, Events } = Matter;
let engine;
let particles = []; // (lava pieces)
let volcano;
let ground;
function setup() {
createCanvas(800, 600);
engine = Engine.create();
// creates a triangular body to represent the volcano
volcano = Bodies.polygon(400, height - 50, 3, 100, { isStatic: true });
// creates a rectangular body to represent the ground
ground = Bodies.rectangle(400, height, 800, 40, { isStatic: true });
// add the volcano and ground to the physics world
World.add(engine.world, [volcano, ground]);
// sets up a collision event listener for the start of collisions
Events.on(engine, 'collisionStart', function(event) {
event.pairs.forEach(pair => {
// to get the two bodies involved in each collision pair
const { bodyA, bodyB } = pair;
// Changes the color of the bodies if they are particles
if (bodyA.render && bodyA.circleRadius) bodyA.render.fillStyle = color(random(255), random(255), random(255));
if (bodyB.render && bodyB.circleRadius) bodyB.render.fillStyle = color(random(255), random(255), random(255));
});
});
}
function draw() {
background(51);
Engine.update(engine); // updates the physics engine
fill(150, 75, 0); // color for volcano
push();
translate(volcano.position.x, volcano.position.y);
rotate(volcano.angle);
triangle(-50, 50, 0, -50, 50, 50); // triangle for volcano
pop();
fill(127);
rectMode(CENTER);
rect(ground.position.x, ground.position.y, 800, 40);
// drawing the particles
particles.forEach(part => {
fill(part.render.fillStyle || [255, 0, 0]); // sets the color of each particle, initializing the color to red to represent lava
ellipse(part.position.x, part.position.y, 10, 10); // shape of each particle
});
}
function mousePressed() {
erupt(); // calls the erupt function
}
function erupt() {
let particle = Bodies.circle(400, height - 150, 5, { restitution: 0.8 });
particle.render.fillStyle = color(255, 0, 0); // initializes the particle color to red
Body.setVelocity(particle, { x: random(-5, 5), y: random(-10, -15) });
particles.push(particle); // adds the particle to the array
World.add(engine.world, particle); // adds the particle to the physics world
// removes old particles for efficiency
if (particles.length > 200) {
let oldParticle = particles.shift(); // removes oldest particle from the array
World.remove(engine.world, oldParticle); // removes oldest particle from the physics world
}
}
function applyWind() {
let windForce = 0.0005; // Strength of the wind force
particles.forEach(particle => {
Body.applyForce(particle, { x: particle.position.x, y: particle.position.y }, { x: windForce, y: 0 });
});
}
function keyPressed() {
if (keyCode === 32) { // keycode for space
applyWind();
}
}