快樂星期天!所以,我只是為了好玩而制作了一個(gè)愚蠢的鴨子狩獵翻拍,我有一個(gè)問題。在畫布中圍繞鼠標(biāo)光標(biāo)制作碰撞框的最佳方法是什么?這是我用來為不同的鴨子設(shè)置動(dòng)畫的代碼,以及用于檢查與邊緣屏幕的碰撞并將它們彈回另一個(gè)方向的代碼。我知道可能有 100 種其他(更好的)方法可以做到這一點(diǎn),但我?guī)缀跏菑牧汩_始制作的,到目前為止我真的很喜歡它。那我想做什么?我需要?dú)Ⅷ喿?。所以?dāng)我點(diǎn)擊一只鴨子時(shí),我可以讓它消失。消失的部分不是問題,我只是不確定如何繼續(xù)。非常感謝任何幫助!這是我的動(dòng)畫和碰撞檢測(cè)代碼:function animateDuckSprites(ducks) { ctx.clearRect(0, 0, canvas.width, canvas.height); ducks.forEach((duck) => { imageFrameNumber++; // changes the sprite we look at imageFrameNumber = imageFrameNumber % totalNumberOfFrames; // Change this from 0 to 1 to 2 ... upto 9 and back to 0 again, then 1... ctx.drawImage( duck.sprite, imageFrameNumber * widthOfSingleImage, 0, // x and y - where in the sprite widthOfSingleImage, heightOfImage, // width and height duck.x, duck.y, // x and y - where on the screen widthOfSingleImage, heightOfImage // width and height ); checkCollision(duck); });}function checkCollision(duck) { if ( duck.x + duck.dx > canvas.width - duck.duckSize || duck.x + duck.dx < 10 ) { duck.dx = -duck.dx; duck.duckRight = !duck.duckRight; duck.sprite.src = duck.duckRight ? duck.spriteRight : duck.spriteLeft; } if ( duck.y + duck.dy > canvas.height - duck.duckSize || duck.y + duck.dy < 25 ) { duck.dy = -duck.dy; } duck.x += duck.dx; duck.y += duck.dy;}謝謝!編輯:剛想出這個(gè)......它有點(diǎn)工作:Pcanvas.addEventListener("click", (e) => { if ( e.screenX >= blueDuck.x + 50 && e.screenX <= blueDuck.x + 200 && e.screenY >= blueDuck.y + 160 && e.screenY <= blueDuck.y + 220 ) { console.log("HIT"); }});
JS - 在畫布中圍繞鼠標(biāo)位置制作一個(gè)hitbox?
守著星空守著你
2022-11-03 14:56:24