您的位置:首页技术文章
文章详情页

js 实现碰撞检测的示例

【字号: 日期:2024-04-13 17:41:32浏览:44作者:猪猪

碰撞检测

目录

代码实例 与简易拖拽的差异 下载源码链接

代码实例

<div style='background: #334;width: 100px;height: 100px;position: absolute;cursor: move;z-index: 999;'></div><div style='background: green;width: 100px;height: 100px;position: absolute;top: 200px;left: 500px;'></div>(function () {var dragging = falsevar boxX, boxY, mouseX, mouseY, offsetX, offsetYvar box = document.getElementById(’box’)var box2 = document.getElementById(’box2’)var box2X, box2Y// 鼠标按下的动作box.onmousedown = down// 鼠标的移动动作document.onmousemove = move// 释放鼠标的动作document.onmouseup = up// 鼠标按下后的函数,e为事件对象function down(e) {dragging = true// 获取元素所在的坐标boxX = box.offsetLeftboxY = box.offsetTop// 获取元素box2所在的坐标box2X = box2.offsetLeftbox2Y = box2.offsetTop// 获取鼠标所在的坐标mouseX = parseInt(getMouseXY(e).x)mouseY = parseInt(getMouseXY(e).y)// 鼠标相对元素左和上边缘的坐标offsetX = mouseX - boxXoffsetY = mouseY - boxY}// 鼠标移动调用的函数function move(e){if (dragging) {// 获取移动后的元素的坐标var x = getMouseXY(e).x - offsetXvar y = getMouseXY(e).y - offsetY// 计算可移动位置的大小, 保证元素不会超过可移动范围var width = document.documentElement.clientWidth - box.offsetWidthvar height = document.documentElement.clientHeight - box.offsetHeight// min方法保证不会超过右边界,max保证不会超过左边界x = Math.min(Math.max(0, x), width)y = Math.min(Math.max(0, y), height)// 给元素及时定位box.style.left = x + ’px’box.style.top = y + ’px’// 碰撞检测// x坐标值的范围判断,y坐标值的范围判断var judge_x = (x >= box2X - box2.offsetWidth) && (x <= box2X + box2.offsetWidth)var judge_y = (y >= box2Y - box2.offsetHeight) && (y <= box2Y + box2.offsetHeight)if (judge_x && judge_y) {console.log('碰撞到')}}}// 释放鼠标的函数function up(e){dragging = false}// 函数用于获取鼠标的位置function getMouseXY(e){var x = 0, y = 0e = e || window.eventif (e.pageX) {x = e.pageXy = e.pageY} else {x = e.clientX + document.body.scrollLeft - document.body.clientLefty = e.clientY + document.body.scrollTop - document.body.clientTop}return {x: x,y: y}}})()

与简易拖拽的差异

简易拖拽的链接

碰撞检测

// 碰撞检测// x坐标值的范围判断,y坐标值的范围判断var judge_x = (x >= box2X - box2.offsetWidth) && (x <= box2X + box2.offsetWidth)var judge_y = (y >= box2Y - box2.offsetHeight) && (y <= box2Y + box2.offsetHeight)if (judge_x && judge_y) {console.log('碰撞到')}

下载源码链接

星辉的Github

以上就是js 实现碰撞检测的示例的详细内容,更多关于js 碰撞检测的资料请关注好吧啦网其它相关文章!

标签: JavaScript
相关文章: