[英]JS - Making a hitbox around mouse position in canvas?
happy Sunday!快乐星期天!
So, I'm making a silly duck hunt remake just for fun, and I got a question.所以,我只是为了好玩而制作了一个愚蠢的鸭子狩猎翻拍,我有一个问题。 What would be the best way to make a hitbox around the mouse cursor in canvas?在 canvas 中围绕鼠标 cursor 制作碰撞框的最佳方法是什么?
This is the code that I use to animate different ducks, and the code to check collision with the edged screen, and bounce them back in another direction.这是我用来为不同的鸭子设置动画的代码,以及用于检查与边缘屏幕的碰撞并将它们弹回另一个方向的代码。
I know there are probably 100 other ( better ) ways to make this, but I made this from scratch pretty much, and I really like it so far.我知道可能还有 100 种其他(更好的)方法可以制作这个,但我几乎是从零开始制作的,到目前为止我真的很喜欢它。
So what do I want to do?那我想做什么? I need to kill ducks.我需要杀鸭子。 So when I click on a duck, I can make it disappear.所以当我点击一只鸭子时,我可以让它消失。 The disappearing part is not the problem, I am just unsure on how to go on about this.消失的部分不是问题,我只是不确定如何解决这个问题。
Any help is highly appreciated!非常感谢任何帮助!
Here is my code for animation and collision detection:这是我的 animation 和碰撞检测代码:
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;
}
Thanks!谢谢!
edit: Just came up with this...it kind of works:P编辑:刚想出这个......它有点工作: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");
}
});
Just came up with this...it kind of works:P刚想出这个......它有点工作: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");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.