I’m making a visual representation of a “paper, rock, scissors” on canvas in Javascript. The point of it is that the objects will randomly flow on the canvas and when collision happens, rule from the original game will be applied. Paper = “beige”, rock = “gray”, scissors = “red”.
Now, the problem is – sometimes the objects are not changing their colors even when if is passing its statements fine – that’s my main problem. But they’re also sometimes are blocking each other and getting stuck.
At first, i thought that only paper (beige) is problematic, but now i don’t know.
I really hope you can find an answear for my problem and explain what am I missing 😀
canvas = document.getElementById('gameCanvas');
canvas.width = window.innerWidth / 2;
canvas.height = window.innerHeight / 2;
var ctx = canvas.getContext("2d");
let enemies = [];
class Obj {
constructor(c) {
this.x = 50 + Math.random() * canvas.width;
this.y = 50 + Math.random() * canvas.height;
this.w = 40;
this.h = 50;
this.c = c;
this.vx = 1;
this.vy = 1;
}
draw() {
ctx.fillStyle = this.c;
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.beginPath();
ctx.lineWidth = 50;
ctx.strokeStyle = "black";
ctx.stroke();
}
update() {
if (this.x + this.w >= canvas.width) {
this.vx = -1;
}
if (this.y + this.h >= canvas.height) {
this.vy = -1;
}
if (this.y <= 0) {
this.vy = 1;
}
if (this.x <= 0) {
this.vx = 1;
}
this.x += this.vx;
this.y += this.vy;
this.draw()
}
bounceOffEachOther(other) {
const dx = this.x + this.vx - other.x;
const dy = this.y + this.vy - other.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.w && this !== other) {
this.vx = -this.vx;
this.vy = -this.vy;
if (this.c == "gray" && other.c == "red" || this.c === "red" && other.c == "grey") {
//console.log("1 " + this.c + " " + other.c);
this.c = "gray";
} else if (this.c == "gray" && other.c == "beige" || this.c == "beige" && other.c == "grey") {
//console.log("2 " + this.c + " " + other.c);
this.c = "beige";
} else if (this.c == "red" && other.c == "beige" || this.c == "beige" && other.c == "red") {
//console.log("3 " + this.c + " " + other.c);
this.c = "red";
}
}
}
}
function createEnemies() {
for (let i = 0; i <2; i++) {
enemies.push(new Obj('grey'));
enemies.push(new Obj('red'));
enemies.push(new Obj('beige'));
}
}
createEnemies();
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach(e => {
e.update();
enemies.forEach(other => e.bounceOffEachOther(other));
});
}
function animate() {
draw();
requestAnimationFrame(animate);
}
animate();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<center><canvas id="gameCanvas" style="border-style:solid; margin-top:10%"></canvas></center>
<script src="script.js"></script>
</body>
</html>