在Vue3中,可以使用getBoundingClientRect()方法来获取元素的位置和大小信息。通过比较两个元素的位置信息,可以判断它们是否发生碰撞,并获取碰撞的方向。

以下是一个示例代码,演示如何校验一个移动的div与多个div是否发生碰撞并获取碰撞方向:

<template>
  <div>
    <div class='container'>
      <div class='movable' :style="{ top: movableTop + 'px', left: movableLeft + 'px' }">
        Movable
      </div>
    </div>
    <div v-for='item in divs' :key='item.id' class='collision-div'>
      Collision Div {{ item.id }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      movableTop: 0,
      movableLeft: 0,
      divs: [
        { id: 1, top: 100, left: 100, width: 200, height: 200 },
        { id: 2, top: 300, left: 300, width: 200, height: 200 },
        // Add more collision divs here
      ],
    };
  },
  mounted() {
    // Listen to mousemove event to update movable div position
    document.addEventListener('mousemove', this.updateMovablePosition);
  },
  beforeUnmount() {
    // Remove event listener when component is unmounted
    document.removeEventListener('mousemove', this.updateMovablePosition);
  },
  methods: {
    updateMovablePosition(event) {
      // Update movable div position based on mouse position
      this.movableTop = event.clientY;
      this.movableLeft = event.clientX;

      // Check collision with each collision div
      this.divs.forEach((div) => {
        const movableRect = this.$refs.movable.getBoundingClientRect();
        const divRect = this.$refs[`div_${div.id}`].getBoundingClientRect();

        // Check collision in each direction
        const isCollide = movableRect.left < divRect.right &&
          movableRect.right > divRect.left &&
          movableRect.top < divRect.bottom &&
          movableRect.bottom > divRect.top;

        if (isCollide) {
          // Determine collision direction
          const collisionDirection = {
            top: movableRect.bottom <= divRect.top,
            bottom: movableRect.top >= divRect.bottom,
            left: movableRect.right <= divRect.left,
            right: movableRect.left >= divRect.right,
          };

          console.log('Collision with div', div.id, 'in direction:', collisionDirection);
        }
      });
    },
  },
};
</script>

<style>
.container {
  position: relative;
  width: 600px;
  height: 400px;
  border: 1px solid black;
}

.movable {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: red;
}

.collision-div {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: blue;
  color: white;
}
</style>

在上述代码中,我们使用mousemove事件监听器来更新可移动div的位置。然后,我们使用getBoundingClientRect()方法获取可移动div和每个碰撞div的位置信息,并检查它们是否发生碰撞。如果发生碰撞,我们使用条件语句判断碰撞方向,并在控制台输出碰撞信息。

请注意,我们为每个碰撞div添加了一个ref属性,以便在代码中引用它们。这样可以通过this.$refs来获取相应的DOM元素,并使用getBoundingClientRect()方法获取其位置信息。

此示例仅针对一个可移动div与多个碰撞div进行碰撞检测和方向判断。您可以根据实际需求进行修改和扩展。


原文地址: https://www.cveoy.top/t/topic/pkrm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录