I am new to using JS scripts and extensions, and I am currently experimenting with smaller projects to learn more about the language. I am currently working on a project for a university assignment and I am using Matter.js and p5.js libraries to create a simulation of spheres colliding with each other and bouncing off walls.
I have created a number of circles using Matter.js and enabled mouse interactions with them using MouseConstraint.
However, when I drag a sphere too quickly, it often goes off the edge of the canvas and disappears. I've tried adjusting the restitution of the spheres as well as the walls and ground of the simulation and the parameters of MouseConstraint, but the issue still persists.
Can anyone suggest a solution or offer any advice on what might be causing this issue?
let engine;
let world;
let spheres = [];
function setup() {
const canvas = createCanvas(windowWidth, windowHeight);
engine = Matter.Engine.create();
world = engine.world;
world.gravity.y = 0.8;
const radius = 25;
const distanceBetweenSpheres = 2 * radius + 50; // adjust the space between spheres
const totalWidth = 2 * distanceBetweenSpheres;
for (let i = 0; i < 3; i++) {
const x = (width - totalWidth) / 2 + i * distanceBetweenSpheres;
const y = 50;
spheres.push(new Sphere(x, y, radius));
}
const ground = Matter.Bodies.rectangle(width / 2, height + 25, width, 50, { isStatic: true });
Matter.World.add(world, ground);
// Create visible walls
const wallOptions = { isStatic: true, render: { fillStyle: '#ED1C24' } };
const leftWall = Matter.Bodies.rectangle(0, height / 2, 20, height, wallOptions);
const rightWall = Matter.Bodies.rectangle(width, height / 2, 20, height, wallOptions);
const ceiling = Matter.Bodies.rectangle(width / 2, 0, width, 20, wallOptions);
Matter.World.add(world, [leftWall, rightWall, ceiling]);
// Enable mouse interactions
const mouse = Matter.Mouse.create(canvas.elt);
const mouseParams = {
mouse: mouse,
constraint: {
stiffness: 0.1,
render: {
visible: false,
},
},
};
const mouseConstraint = Matter.MouseConstraint.create(engine, mouseParams);
Matter.World.add(world, mouseConstraint);
// Make the canvas scalable
canvas.elt.addEventListener('mousedown', (e) => e.preventDefault());
}
function draw() {
background(240);
Matter.Engine.update(engine);
for (let sphere of spheres) {
sphere.show();
}
}
class Sphere {
constructor(x, y, r) {
this.body = Matter.Bodies.circle(x, y, r, { restitution: 0.5 });
this.r = r;
Matter.World.add(world, this.body);
}
show() {
const pos = this.body.position;
push();
translate(pos.x, pos.y);
ellipse(0, 0, this.r * 2);
pop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.min.js"></script>