码迷,mamicode.com
首页 > Web开发 > 详细

js碰撞

时间:2014-11-26 01:02:28      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   java   strong   

两个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碰撞

标签:style   blog   io   ar   color   os   sp   java   strong   

原文地址:http://www.cnblogs.com/5huihui/p/4122132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!