带有CSS动画的javascript碰撞检测

标签 javascript html css collision-detection

我有以下“游戏”:

jsfiddle

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/

相关文章:

javascript - 为什么这个 javascript 代码不起作用?

javascript - 用js中数组中的其他字符替换特殊字符

javascript - 右对齐 Highcharts 栏

javascript - 获取类内的 tagName 元素

html - 减少 HTML 中两行之间的间距

javascript - 将解析图像文件转换为 base64 以保存在 zip 文件中

html - 列表样式类型 : none does not work in the removal of bullets(dots) attached with items in the navigation bar

html - 使用图像作为可点击的 anchor 链接

javascript - 在 Django 应用程序中引用 JS/CSS 文件的最基本方法是什么?

html - 如何在不嵌套 anchor 的情况下向嵌套的 div 标签添加链接?