快乐星期天!所以,我只是为了好玩而制作了一个愚蠢的鸭子狩猎翻拍,我有一个问题。在画布中围绕鼠标光标制作碰撞框的最佳方法是什么?这是我用来为不同的鸭子设置动画的代码,以及用于检查与边缘屏幕的碰撞并将它们弹回另一个方向的代码。我知道可能有 100 种其他(更好的)方法可以做到这一点,但我几乎是从零开始制作的,到目前为止我真的很喜欢它。那我想做什么?我需要杀鸭子。所以当我点击一只鸭子时,我可以让它消失。消失的部分不是问题,我只是不确定如何继续。非常感谢任何帮助!这是我的动画和碰撞检测代码: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;}谢谢!编辑:刚想出这个......它有点工作: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"); }});
1 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
刚想出这个......它有点工作:P
canvas.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");
}
});
添加回答
举报
0/150
提交
取消