Ask coding questions

← Back to all posts
Bullets completely broken
h
javakid999

Okay. So i am working on this project. The collisions seemed to be working fine, but instead of shooting bullets freely, it shoots them one at a time. Is there anyway to fix this?
P.S. Sorry if my code is unreadable im not too good at javascript

Answered by MatthewDoan1 [earned 5 cycles]
View Answer
Voters
javakid999
Comments
hotnewtop
MatthewDoan1

The problem was with your drawBullets() and collisionCheck() methods. You see, this was your drawBullets() function:

and this was your collisionCheck() function:

Even though I'm not that good at js (I learned it ~2 years ago and never used it since, besides for some simple NodeJS projects), I noticed this: In drawBullets(), you're looping through the bullets, and then in collisionCheck() you're looping through the bullets again! Suppose you have n bullets. For each bullet, you do n collision checks. In the end you get n^2 collision checks. Here's how I improved your code:

See the difference? Instead of performing collision checks with every single bullet when a SINGLE bullet is drawn, instead you perform collision checks only with that bullet.

If you test out this code in your JavaScript, you'll notice something like this:

To prevent this, I recommend you take a look at the KeyDrown JavaScript library.

Here's the repl that I created, if you'd like to take a look at the modified code.

Ciao for now! If you have any questions, feel free to respond to this comment.

javakid999

@MatthewDoan1 Thanks so much! This will really help. I will also definitely take a look at the key drown library.