js碰撞
两个div从不同方向、用不等的速度移动。
html:
<div id="box1" style="width: 100px;height: 100px;background: darkolivegreen;position: absolute;left: 50px;"></div> <div id="box2" style="width: 100px;height: 100px;background: seagreen;position: absolute;left: 800px;top: 150px;"></div>
javascript:
var lastTime = Date.now(); var boxSpeed1 = 100; var boxSpeed2 = 150; var box1 = document.getElementById(‘box1‘); var box2 = document.getElementById(‘box2‘); function main(){ var nowTime = Date.now(); var dt = (nowTime - lastTime) / 1000; box1.style.left = parseInt(box1.style.left) + boxSpeed1 * dt + ‘px‘; box2.style.left = parseInt(box2.style.left) - boxSpeed2 * dt + ‘px‘; lastTime = nowTime; setTimeout(main,1000/60); } main();
两个div从不同方向、用不等的速度移动,判断两个div碰撞,这经常用在游戏敌机与本机碰撞爆咋或者子弹打到敌机爆炸。
html:
<div id="box1" style="width: 100px;height: 100px;background: darkolivegreen;position: absolute;left: 50px;"></div> <div id="box2" style="width: 100px;height: 100px;background: seagreen;position: absolute;left: 800px;"></div>
javascript:
var lastTime = Date.now(); var boxSpeed1 = 100; //从左边走的div速度 var boxSpeed2 = 150; //从右边走的div速度 var box1 = document.getElementById(‘box1‘); var box2 = document.getElementById(‘box2‘); function main(){ var nowTime = Date.now(); var dt = (nowTime - lastTime) / 1000; var recA = getDemosion(box1); var recB = getDemosion(box2); var flag = cili(recA,recB); if(flag){ alert(‘爆炸‘); return; } else{ box1.style.left = parseInt(box1.style.left) + boxSpeed1 * dt + ‘px‘; box2.style.left = parseInt(box2.style.left) - boxSpeed2 * dt + ‘px‘; } lastTime = nowTime; setTimeout(main,1000/60); } main(); function getDemosion(element){ return { x:element.offsetLeft, y:element.offsetTop, width:element.offsetWidth, height:element.offsetHeight } } function cili(rectA,rectB){ return !( rectA.x + rectA.width < rectB.x || rectB.x + rectB.width < rectB.x || rectA.y + rectA.height < rectA.y || rectB.y + rectB.height < rectB.y ) }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。