首页 > 代码库 > js碰撞
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 ) }
js碰撞
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。