1. 程式人生 > 程式設計 >js 實現碰撞檢測的示例

js 實現碰撞檢測的示例

碰撞檢測

目錄

  • 程式碼例項
  • 與簡易拖拽的差異
  • 下載原始碼連結

程式碼例項

<div id="box" style="background: #334;width: 100px;height: 100px;position: absolute;cursor: move;z-index: 999;"></div>
<div id="box2" style="background: green;width: 100px;height: 100px;position: absolute;top: 200px;left: 500px;"></div>

(function () {
	var dragging = false
	var boxX,boxY,mouseX,mouseY,offsetX,offsetY
	var 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.offsetLeft
		boxY = box.offsetTop

		// 獲取元素box2所在的座標
		box2X = box2.offsetLeft
		box2Y = box2.offsetTop

		// 獲取滑鼠所在的座標
		mouseX = parseInt(getMouseXY(e).x)
		mouseY = parseInt(getMouseXY(e).y)

		// 滑鼠相對元素左和上邊緣的座標
		offsetX = mouseX - boxX
		offsetY = mouseY - boxY
	}

	// 滑鼠移動呼叫的函式
	function move(e){
		if (dragging) {
			// 獲取移動後的元素的座標
			var x = getMouseXY(e).x - offsetX
			var y = getMouseXY(e).y - offsetY

			// 計算可移動位置的大小, 保證元素不會超過可移動範圍
			var width = document.documentElement.clientWidth - box.offsetWidth
			var 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 = 0
		e = e || window.event
		
		if (e.pageX) {
			x = e.pageX
			y = e.pageY
		} else {
			x = e.clientX + document.body.scrollLeft - document.body.clientLeft
			y = 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 碰撞檢測的資料請關注我們其它相關文章!