I am creating a pinball game for a school project. I am using p5.js for graphics and Matter.js for the physics. Everything else in my code is working except for the flippers, which keep firing continuously and making gameplay difficult.
I attempted to use attractors to solve the issue such as this repo does here
However my code keeps throwing errors saying that the attracted body is undefined. I don't know what the issue with this is.
My other option is to remove velocity from the body after firing. Unfortunately, this hasn't worked and I don't know why Matter.js does not recognize this issue.
My github repo is here
class Flipper {
constructor(x, y, w, h, isLeft) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.body = Bodies.rectangle(this.x, this.y, this.width, this.height);
this.velocity = 0.2;
this.hingeRadius = 5;
if (isLeft) {
this.hinge = Bodies.circle(this.x - this.width / 2, this.y, this.hingeRadius, { isStatic: true, label: "hinge" });
}
else {
this.hinge = Bodies.circle(this.x + this.width / 2, this.y, this.hingeRadius, { isStatic: true, label: "hinge" });
}
Composite.add(world, this.body);
let options = {
bodyA: this.body,
pointA: isLeft ? { x: - this.width / 2 + 10, y: 0} : { x: this.width / 2 - 10, y: 0 },
bodyB: this.hinge,
length: 0,
stiffness: 1,
};
this.constraint = Constraint.create(options);
Composite.add(world, this.constraint);
}
show() {
// display the flipper
let pos = this.body.position;
let angle = this.body.angle;
push();
translate(pos.x, pos.y);
rotate(angle);
rectMode(CENTER);
fill(100);
noStroke();
rect(0, 0, this.width, this.height);
pop();
let hingePos = this.hinge.position;
push();
translate(hingePos.x, hingePos.y);
fill(255);
noStroke();
circle(0, 0, this.hingeRadius);
pop();
}
hit(isLeft) {
if (isUp) {
if (isLeft) {
console.log(isUp);
Body.setAngularVelocity(this.body, -this.velocity);
// isUp = false;
}
else {
console.log(isUp);
Body.setAngularVelocity(this.body, this.velocity);
// isUp = false;
}
}
else {
Body.setAngularVelocity(this.body, 0);
}
}
}
// WASD to control flipper movement
function keyPressed() {
if (key === " ") {
if (gameState === "start") {
if (!bgMusic1.isPlaying()) {
bgMusic1.play();
}
gameState = "play";
}
}
if (key === "a") {
isUp = true;
lFlipper.hit(true);
}
if (key === "d") {
isUp = true;
rFlipper.hit(false);
}
}
// just to release flippers
function keyReleased() {
if (key === "a") {
isUp = false;
lFlipper.hit(true);
}
if (key === "d") {
isUp = false;
rFlipper.hit(false);
}
if (key === " ") {
if (gameState === "play") {
pinball.launch();
}
}
}