I've created a slingshot game in matter.js where I've created a ball which is used as a sling and some target balls on a ground which should be pushed off. I've attached the code below. I need help in tracking score so that everytime time user pushes all the balls off the ground "You won!" message should be displayed. Also need help in adding reset button. Link to the live game
let engine = Matter.Engine.create();
let render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 1600,
height: 800,
wireframes: false
}
});
let ground = Matter.Bodies.rectangle(1200, 500, 300, 60, { isStatic: true });
let mouse = Matter.Mouse.create(render.canvas);
let mouseConstraint = Matter.MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
render: {visible: false}
}
});
render.mouse = mouse;
let ball = Matter.Bodies.circle(300, 600, 20);
let sling = Matter.Constraint.create({
pointA: {x:300, y:600},
bodyB: ball,
stiffness: 0.05
})
let stack = Matter.Composites.stack(1100, 270, 4, 4, 0, 0, function(x, y){
return Matter.Bodies.polygon(x, y, 8, 30);
});
let firing = false;
Matter.Events.on(mouseConstraint, 'enddrag', function(e){
if(e.body === ball) firing = true;
});
Matter.Events.on(engine, 'afterUpdate', function(){
if(firing && Math.abs(ball.position.x-300)<200 && Math.abs(ball.position.y-600)<20){
ball = Matter.Bodies.circle(300, 600, 20);
Matter.World.add(engine.world, ball);
sling.bodyB = ball;
firing = false;
}
})
Matter.World.add(engine.world, [stack, ground,ball, sling, mouseConstraint]);
Matter.Engine.run(engine);
Matter.Render.run(render);