The divs are crashing into each other and moving at varying speeds

I have created a mini game inspired by diep.io on codepen, where you can upgrade your reload and shooting capabilities. However, I have encountered an issue where the bullets start moving at different speeds and end up overlapping each other after shooting more than twice. Check it out for yourself here:

https://codepen.io/TheAndersMan/pen/gwKmYy

Below is the HTML code:

    <div class="wrap">
      <div class="body"></div>
      <div class="barrel"></div>
      <div class="bullets">
      </div>
    </div>

Here is the CSS code:

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

And here is the JavaScript code:

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

It might seem like a lot, but I wanted to provide you with the complete picture. It would be easier to understand if you viewed the code on the pen itself.

If you can help me figure out why the bullets are changing speeds and overlapping, I would greatly appreciate it.

Answer №1

Check out my version here.

Let me share my perspective on this situation.

The approach involves creating a div.bullet within the .bullets container and animating it using left-margin. However, using margin in this way causes a displacement without actually moving the item, as it impacts the inline flow and creates a gap rather than true motion. (When using display:flex, elements behave more like inline than block-level.)

For instance, consider three sibling elements set to display:inline. Applying margin-left to the second element would affect both the second and third elements' positions.

In my version, I opted for absolute positioning and utilized left for placement. This removes the elements from the normal document flow, eliminating their influence on surrounding elements. (I made some adjustments to z-index as well.)

It seems like you attempted a similar approach, but the missing position:absolute on the parent element caused positioning problems.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for opening a local HTML file in IE compatibility mode?

Having issues with IE compatibility mode while opening my HTML file on desktop. In IE8, unable to switch it to compatibility mode as the icon seems to disappear in local HTML documents. Any insights on this? LATEST UPDATE: Tried three solutions but still ...

Transform an array into an object utilizing only underscore

I'm currently learning about underscore and came across a task that I could use some assistance with. I have an array containing objects like the following: [ // ... { "type": "presence", "params": { "i ...

Assign an onClick event to a Button that was dynamically generated within a loop in JavaScript

Is there a way to set the onClick property for buttons created within a loop? I've tried using JQuery with no success. for(started somewhere... var button = document.createElement('button') var div = document.createEl ...

There seems to be an issue with the item display page when clicking on the 'view details' button within the Bootstrap tab

Encountering a problem with displaying the product details page. There are four bootstrap tabs, each containing some Product Items with a Quick View link button. The issue arises when clicking on the link button, as all tab items with the same ID are displ ...

The iisnode encountered an issue with HRESULT 0x6d resulting in a status code of 500 and a substatus of 1013

Despite trying multiple solutions, none seemed to work for my Node.js website hosted on Windows IIS with iisnode. Everything was running smoothly until today when I encountered an interesting situation. Let's say my domain is cdn1.site.com and it&apos ...

Using Javascript code to draw particles at the cursor's position and then directing those particles towards the bottom of

I found an interesting JavaScript code snippet that creates a bubble particles effect around the cursor. You can download it from https://github.com/tholman/90s-cursor-effects. However, I encountered a problem when adding certain elements inside a specifi ...

What is the reason that self focus doesn't function in JavaScript?

Whenever an input element triggers a blur event, I want to focus on a specific element. The issue arises when I try to focus on the same element that caused the blur event. Why does this only work when the element I am focusing on is not the one triggeri ...

Is it possible to have the Save Success Alert fade out only once?

After incorporating this code snippet, I implemented a fade effect on the success alert whenever it is triggered. However, I noticed that the fade effect only occurs the first time I click "save". Subsequent clicks do not trigger the fade effect, causing ...

Updating or adding items to an array using underscore library

A scenario involves an object with incoming data and an array that contains saved data. The goal is to check if the "cnName" from the new data already exists in the "savedData" array. If it does, then the object in "savedData" should be replaced with the n ...

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

Repetitive series of HTTP requests within a looping structure

Within my AngularJS project, I encounter the need to execute a varying number of HTTP requests in sequence. To achieve this, I believe that utilizing a loop is necessary: for (let i = 0; i < $scope.entities.length; i++) { MyService.createFixedValue ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

What is the best way to identify when a page has been refreshed in Reactjs?

Imagine a set of pages with steps: 1, 2, and 3. If a page reloads during the second or third step, it must be directed back to the first step. Is there a way to identify when a page has been reloaded? ...

Unable to customize the button color within the Bootstrap framework

This button was created using Bootstrap. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <lin ...

outdoor checkboxes indicate completion

Whenever I click on the email address example [email protected], my first checkbox gets checked inexplicably... I have created a fiddle to demonstrate this issue... http://jsfiddle.net/pZ8jY/ <table class="checkboxes"> <tr> <td ...

HTML <section> Order Placement

I am currently facing an issue with the placement of two divs on my html page. I have a navigation bar and another content div, but they are not appearing in the right order. This is how my html structure looks: <html> <body> <div id="navig ...

Angular cookies may expire, but using the back button always revives them

Utilizing angular's cookie library, I have successfully set a cookie to store the id and passcode of a shopping cart on the backend. However, despite setting the expiration date to a past time in order to expire the cookie once the cart is purchased, ...

Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading: <div id="customerdetailsDIV" class="well main-well clearfix"> @Html.Partial("_customer_details", Mod ...