我正在codepen上製作diep.io迷你遊戲,您可以升級重新加載和拍攝,但是當您拍攝兩次以上時,子彈以不同的速度前進並相互重疊。 你可以在這裏看到自己:Divs重疊並出錯速度
https://codepen.io/TheAndersMan/pen/gwKmYy
這裏是我的HTML:
<div class="wrap">
<div class="body"></div>
<div class="barrel"></div>
<div class="bullets">
</div>
</div>
這裏是我的CSS:
.wrap {
position: absolute;
top: 30vh;
left: 40vw;
display: flex;
}
.wrap .body {
width: 200px;
height: 200px;
background: #00b2e1;
border-radius: 100%;
border: 6px solid black;
z-index: 1;
}
.wrap .barrel {
width: 150px;
height: 125px;
background: #666;
margin-top: calc(75px/2);
margin-left: -50px;
z-index: 0;
border: 6px solid black;
}
.wrap .bullets {
margin-top: calc(75px/2);
margin-left: -125px;
display: flex;
}
.wrap .bullets .bullet {
width: 125px;
height: 125px;
border-radius: 100%;
background: #F14E54;
border: 6px solid black;
animation: bulletMove 3s linear 1;
}
@keyframes bulletMove {
0% {
margin-left: -125px;
}
100% {
margin-left: 60vw;
}
}
而我的JS:
var fireRate = 1,
fireInterval = null,
loadNum = 0;
function fire() {
console.log("BAM!");
let bullet = document.createElement("div");
document.body.appendChild(bullet);
bullet.classList.add("bullet");
setTimeout(function() {
bullet.remove();
}, 2000)
document.querySelector(".bullets").appendChild(bullet);
}
function startFire() {
fire();
fireInterval = setInterval(fire, 1000/fireRate);
}
function stopFire() {
clearInterval(fireInterval);
}
對不起,這很多,我只是想給你(幾乎)完整的圖片,如果你真的去了筆,看到它自己,它可能會更有意義。
所以,如果你能幫助我解決爲什麼子彈改變速度和重疊,這將是偉大的。
我認爲它發生的是,div在「讓子彈」內創建。當你再次調用它時,已經有一個它正在運行的實例,所以它從當前項目符號開始,不重疊,從當時第一個項目符號的起始位置開始,然後從第二個項目符號開始開始。您可能想要改變您創建div元素的方式以及您如何追加這些孩子? – Leo
@Leo我會怎麼做呢? – TheAndersMan
也許試圖在每次觸發時創建一個不同的子彈變量?我認爲這是你的問題,如果我是在JQuery中,例如,我會克隆該元素,使其與其他.bullet DOM元素分開 – Leo