vue3 wasd按键控制div 上下左右移动 并且验证是否与其它指定div发生碰撞 打印输出
在Vue 3中,你可以使用键盘事件监听来实现WASD按键控制div的移动,并使用碰撞检测算法来验证其与其他指定div是否发生碰撞。以下是一个简单的实现示例:
在template中,你需要定义一个div元素,并通过绑定样式的方式控制其位置:
<div
ref="movableDiv"
:style="{ top: position.y + 'px', left: position.x + 'px' }"
></div>
在script中,你需要定义data属性来追踪div的位置和键盘按键的状态:
data() {
return {
position: {
x: 0,
y: 0
},
keys: {
w: false,
a: false,
s: false,
d: false
},
otherDivs: [
// 其他指定的div,用于碰撞检测
{ top: 100, left: 100, width: 50, height: 50 },
{ top: 200, left: 200, width: 50, height: 50 }
]
}
},
接下来,你需要在mounted生命周期钩子中添加键盘事件监听器,并在methods中定义相应的移动和碰撞检测逻辑:
mounted() {
window.addEventListener('keydown', this.handleKeyDown);
window.addEventListener('keyup', this.handleKeyUp);
},
methods: {
handleKeyDown(event) {
const key = event.key.toLowerCase();
if (key === 'w' || key === 'a' || key === 's' || key === 'd') {
this.keys[key] = true;
}
},
handleKeyUp(event) {
const key = event.key.toLowerCase();
if (key === 'w' || key === 'a' || key === 's' || key === 'd') {
this.keys[key] = false;
}
},
moveDiv() {
if (this.keys.w) {
this.position.y -= 10;
}
if (this.keys.a) {
this.position.x -= 10;
}
if (this.keys.s) {
this.position.y += 10;
}
if (this.keys.d) {
this.position.x += 10;
}
this.checkCollision();
},
checkCollision() {
const movableDiv = this.$refs.movableDiv;
const movableRect = movableDiv.getBoundingClientRect();
for (const div of this.otherDivs) {
const rect = {
top: div.top,
left: div.left,
right: div.left + div.width,
bottom: div.top + div.height
};
if (
movableRect.top < rect.bottom &&
movableRect.bottom > rect.top &&
movableRect.left < rect.right &&
movableRect.right > rect.left
) {
console.log('碰撞发生!');
}
}
}
}
最后,你可以在mounted生命周期钩子中使用setInterval来定时调用moveDiv方法,以实现持续的移动效果:
mounted() {
window.addEventListener('keydown', this.handleKeyDown);
window.addEventListener('keyup', this.handleKeyUp);
setInterval(this.moveDiv, 100);
}
这样,当你按下W、A、S或D键时,div将会向相应的方向移动,并且会检测与其他指定div的碰撞情况,并在控制台打印输出
原文地址: https://www.cveoy.top/t/topic/iyel 著作权归作者所有。请勿转载和采集!