太空射击 - 射击功能

时间:2018-03-29 10:09:58

标签: javascript html

我的代码运行有问题。我想创造射击游戏的效果,但是当我创建一个div时,我必须等到它完成动画才创建另一个,我怎么能做到?请帮忙。

function createShot (){
 div[i] = document.createElement("div");
 screen.appendChild(div[i]);
div[i].style.height = 5 + "px";
div[i].style.position = "absolute";
div[i].style.border = 2 + "px solid #F30";
div[i].style.width = 5 + "px";
div[i].style.left = x+3 + "px";
div[i].style.top = divy + "px";
t = setInterval (shot,1);
}
function shot (){
    if (divy <= 0){
        screen.removeChild(div[i]);
          divy = 260;
          clearInterval (t);
    } else {
          divy -= 5;
         div[i].style.top = divy + "px";
    }
}
tshoot = setInterval(createShot,1000);

1 个答案:

答案 0 :(得分:0)

看起来我是全局的而不是递增的,所以你不能同时拥有多个拍摄实例。依赖全局变量是一种不好的做法,尤其是在异步环境中。这是一个有效的例子:

var shoot = function(div)
{ 
    var x = parseInt(div.style.left); 
    x++;
    if (x>1000) {
        clearInterval(div.t); 
        document.body.removeChild(div);
        return;
    } 
    div.style.left = x+'px'; 
}    
var createShot = function(){ 
    var div = document.createElement('div');div.style.height = 5 + "px";
    div.style.position = "fixed";
    div.style.border = "5px solid red";
    div.style.width = "5px";
    div.style.left = "0px";
    div.style.top = "100px";
    document.body.appendChild(div); 
    div.t = setInterval(shoot, 10, div);
}
setInterval(createShot, 200)