gpt4 book ai didi

javascript - Div重叠并且速度错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:18 25 4
gpt4 key购买 nike

我正在 codepen 上制作一个 diep.io 小游戏,你可以升级装填和射击,但是当你射击超过两次时,子弹以不同的速度移动并且相互重叠。你可以在这里亲眼看到:

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);
}

抱歉,太多了,我只想给你(几乎)全貌,如果你真的去笔下亲眼看看,可能会更有意义。

因此,如果您能帮我解决子弹改变速度和重叠的原因,那就太好了。

最佳答案

My variant.

所以这就是我认为正在发生的事情。

您创建 div.bullet 并将其附加到 .bullets 容器。然后使用 left-margin 为它们设置动画。问题是,边距会插入元素和所有后来的 sibling ,因为它会影响内联流,本质上是创造了一个差距,而不是真正移动任何东西。 (display:flex 使它们本质上是内联的而不是 block 级的。)

假设您有三个元素,它们是同级元素,并且被设置为 display:inline。在第二个上设置 margin-left 会导致第二个和第三个都改变位置。

在我的变体中,我切换到绝对定位并使用 left 来定位它们。这使它们脱离了文档的正常流程,因此它们不再对周围的元素产生影响。 (我还稍微更改了 z-index。)

我注意到您似乎尝试过这样做,但看起来您也没有将 position:absolute 放在父级上,因此定位搞砸了。

关于javascript - Div重叠并且速度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com