Should this For-Loop, in theory, work?
I have a question on collision detection for a similar problem, but it is not exactly the same. I am having a problem with a new game project (I am trying to learn more about HTML5 and Socket.io canvases) where my collisions were not working. I thought my question was focused on collisions, but now I'm starting to think about something else. The reason I have another issue posted here in the for-loop scope is because I'm not sure if my problem is with loop binding or collision detection. Anyway, I would be happy to answer one of my questions.
This code loops each frame to get the active positions of bullets and ships. If the bullet touches the ship, it will be removed and some health points will be removed from the ship.
The tutorial I used: http://jlongster.com/Making-Sprite-based-Games-with-Canvas
As an aside, here's my checkCollisions code. The collision function seems to work because when I started registering all positions every time we had an iteration, it seemed like the position of my object was changing every time. Is this one of the problems for the loop when I need a callback?
Thank you so much for your help. I will definitely answer / choose every answer that helps! :)
DECIDE! It turns out one of my arrays didn't get through correctly. I would like to thank you guys for telling me to always divide it into multiple functions, which really helped me figure out which one is!
// Let start out here: I have a players[] array
//that essentially a list of all players on the server
// and their positions. I omitted server connection functionality since that not my error
// source.
function checkCollisions() {
for (var i = 0; i < players.length; i++) { // Iterating through all players
var pos = [players[i].posX, players[i].posY];
var size = [SHIP_WIDTH, SHIP_HEIGHT]; // This is the size of each player, it a ship game. So these are constants.
if (players[i].userId != PLAYER.userId) { // Each player has a userId object, this is just doublechecking if we're not uselessly iterating
for (var j = 0; j < bullets.length; j++) { // We're now looping through bullets, an array of all the bullets being shot by players
var pos2 = bullets[j].pos;
var size2 = BULLET_SIZE;
var sender = bullets[j].sender;
if (boxCollides(pos, size, pos2, size2)) { // Collision code
if (sender != players[i].userId) {
bullets.splice(j, 1);
i--; // Tried here with j--, and by removing the entire line. Unfortunately it doesn't work :(
break;
}
}
}
}
}
}
source to share
Have you tried using console.log to see where the program is running? This can help you determine if there are multiple errors or just that. If there is something wrong in the previous statement, you may not be aware of it if you corrected i - / j --...?
Edit: AH I see you fixed everything after I posted this. Well congratulations and working!
source to share