I've been working on a small JavaScript Zombie game using the p5 library. The goal is to keep track of hits when clicking on a Zombie and misses when failing to hit one. However, I'm facing an issue where 10 results are displayed per click when there are 10 Zombies in the array. Finding a solution has been challenging and I don't want to complicate the game with messy code. Thank you for any help!
// object storing arrays
let zom = [];
let hb = 25;
// player info and ui
;
let hits = 0;
let missed = 0;
function setup() {
let cnv = createCanvas(600, 300, P2D);
let pos = createVector((width / 2), (height / 2));
// zombie spawnpoints
let zp0 = createVector(height / 4 + 35, height / 3);
let zp1 = createVector(width - 35, height / 2);
zom.push(new Zombie(zp0));
zom.push(new Zombie(zp1));
}
function draw() {
background(220);
fill(0);
text("hits: " + hits, 10, 10);
text("missed: " + missed, 10, 20);
for (let i = 0; i < zom.length; i++) {
zom[i].move();
zom[i].show();
}
}
function Zombie(pos) {
this.pos = pos;
Zombie.prototype.move = function() {
this.pos.x += 0.2;
if (this.pos.x > width + hb) {
this.pos.x = -hb
}
}
Zombie.prototype.show = function() {
circle(this.pos.x, this.pos.y, hb);
}
}
function mouseClicked() {
hitBox();
}
function hitBox() {
let mx = mouseX;
let my = mouseY;
for (let i = 0; i < zom.length; i++) {
if (mx > zom[i].pos.x - hb &&
mx < zom[i].pos.x + hb &&
my > zom[i].pos.y - hb &&
my < zom[i].pos.y + hb) {
hits += 1;
} else {
missed += 1;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/addons/p5.sound.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="main.js"></script>
</body>
</html>