我有以下“游戏”:
function update() {
coyote.applyForce(gravity);
coyote.edges();
coyote.update();
cactus.update();
if (coyote.intersects(cactus)){
alert("colision");
}
}
问题是,当coyote 跳跃时,div 会增加它的大小,并且有一些空白点也会导致碰撞。
有什么方法可以改进碰撞检测吗?我曾尝试实现内部 Hitbox,但我不知道如何实现。
最佳答案
花了一段时间才明白你在做什么。
但是如果你为你的播放器取一个静态的宽度和高度。它应该可以解决您的问题。
constructor(){
this.coyote = new Entity();
this.coyote.pos.set(0,222);
this.coyote.vel.set(0,0);
this.coyote.acc.set(0,0);
this.coyote.width = 78;
this.coyote.height = 128;
this.isGrounded = true;
this.state = States.RUNNING;
}
intersects(other) {
let div = document.getElementById("player");
let left = this.coyote.pos.x;
let right = this.coyote.width;
let top = this.coyote.pos.y;
let bottom = this.coyote.height;
let oLeft = other.left;
let oRight = other.right;
let oTop = other.top;
let oBottom = other.bottom;
return !(left > oRight || right < oLeft || top > oBottom || bottom < oTop);
}
这应该适合您。
小贴士:
1. 使用 Canvas 作为启动器。
2.最重要的是可读代码。
3.评论与总结
关于带有CSS动画的javascript碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46862391/