You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复类元素碰撞检测报错及获取div过渡过程中的实时高度

游戏碰撞检测修复与过渡高度实时获取方案

一、修复碰撞检测的TypeError报错

你的代码存在三个核心问题:

  1. 函数内部重新声明fishy变量,覆盖了传入参数,且getElementsByClassName返回的HTMLCollection可能为空,循环结束后fishyRect会变成undefined,导致调用getBoundingClientRect报错;
  2. getBoundingClientRect()方法不需要传入参数i,这是冗余写法;
  3. 原逻辑仅取最后一个鱼的位置信息进行判断,没有遍历所有fish1元素做碰撞检测。

修复后的完整代码:

function checkCollision(rope) {
  const ropeRect = rope.getBoundingClientRect();
  const fishList = document.getElementsByClassName('fish1');
  
  // 遍历所有class为fish1的元素
  for (let i = 0; i < fishList.length; i++) {
    const fishy = fishList[i];
    if (!fishy) continue; // 跳过不存在的元素,避免报错
    const fishyRect = fishy.getBoundingClientRect();
    
    // 检测当前鱼与绳子的碰撞
    const collisionOccurred = (ropeRect.right >= fishyRect.left && ropeRect.left <= fishyRect.right) &&
                              (ropeRect.bottom >= fishyRect.top && ropeRect.top <= fishyRect.bottom);
                       
    if (collisionOccurred) {
      return true; // 只要有一个碰撞就立即返回true
    }
  }
  
  return false; // 所有鱼都未碰撞,返回false
}

二、过渡动画中获取div实时高度

普通的offsetHeight或getBoundingClientRect().height无法在过渡动画中实时更新,需借助requestAnimationFrame同步浏览器重绘帧,实现实时获取:

function trackRealTimeHeight(element) {
  function updateHeight() {
    const currentHeight = element.getBoundingClientRect().height;
    // 这里可以添加你需要的实时高度处理逻辑
    console.log('当前实时高度:', currentHeight);
    
    // 判断过渡动画是否仍在进行
    const style = window.getComputedStyle(element);
    const isAnimating = style.transitionProperty.includes('height') && style.transitionDuration !== '0s';
    
    if (isAnimating) {
      requestAnimationFrame(updateHeight); // 持续监听下一帧
    }
  }
  
  requestAnimationFrame(updateHeight);
}

// 调用示例:监听rope元素的过渡高度变化
const rope = document.getElementById('rope');
trackRealTimeHeight(rope);

如果需要在动画结束后执行回调,可以结合transitionend事件:

rope.addEventListener('transitionend', () => {
  console.log('过渡动画结束,最终高度:', rope.getBoundingClientRect().height);
});

内容的提问来源于stack exchange,提问作者lovelyLuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:05:22