class Snake {
constructor() {
this.x = 400;
this.y = 400;
this.width = 25;
this.height = 25;
}
draw() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
let snake = new Snake();
class Food {
constructor() {
this.x = Math.floor(Math.random() * (canvasWidth - 0) + 0)
this.y = Math.floor(Math.random() * (canvasHeight - 0) + 0)
this.width = 50;
this.height = 50;
/* this.image = new Image()
this.image.src = 'img/apple.png' */
}
update() {
}
draw() {
/* ctx.drawImage(this.image, this.x, this.y, this.width, this.height); */
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
let food = new Food()
function collision(){
if(snake.x < food.x + food.width &&
snake.x + snake.width > food.x &&
snake.y < food.y + food.height &&
snake.height + snake.y > food.y){
alert("hit")
}
}
collision()
I have created two classes in JavaScript, one for a snake and the other for food. I am attempting to implement a collision algorithm I found, but it doesn't seem to be working properly. Can anyone help me identify the mistake or suggest a better way to handle collisions?