简体   繁体   中英

Collision detection in html5 canvas between two squares

 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 two JS classes one portrays a snake the other portrays food, I tried this collision algorithm I found but it's not working. where is my mistake or how can I make the collision happen?

Just had to call collision() in the animate function

 function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); snake.draw(); snake.update(); food.draw() collision() requestAnimationFrame(animate); } animate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM