繁体   English   中英

html5 canvas 中两个方格之间的碰撞检测

[英]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()

我有两个 JS 类,一个描绘了一条蛇,另一个描绘了食物,我尝试了我发现的这种碰撞算法,但它不起作用。 我的错误在哪里或如何使碰撞发生?

只需在动画 function 中调用碰撞()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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