About loops, updates

How to properly program this

lets say I have a for loop which checks if an object collides on another object.
Do I have to continue; ? or break; if collided?

Depends on what you want to do, continue and break are just some control mechanism

Usually you can just do

if(player collides with bullet)
{
  player.hp -= damage
}

long loops can cause app to lag right?

so that’s why there’s a need for break/continue?

I am currently working with collisions as well and I am a noob with
cocos2d, but I feel that using a for loop to check if objects is
colliding with each other will cause serious performance issues.

for( list of obj A) {
for (list of obj B){
if(A!=B && A.pos == B.pos){
//collision
}
}
}

Imaging checking for collusion every frame, this will cost:
frames*O(x^2). Which is not ideal. And I believe if you put loops inside
updates, it might cause problems if update is called before for loop
finishes.

Take a look at b2ContactListener. I.m not sure what the equivalent is for Chipmunk if you are using that, but the idea is that the physics engine will tell you when a collision occurs, which is way more performant than looping over everything and testing for a collision.

That’s true. will really cause serious performance issues

So far my game is smoother now. what I did is that every collision I break;
ex.

(assuming that this is a for loop, loop each bullet, etc.)
if(player collides with bullet)
{
player.hp -= damage
break;
}

if(player collides with buildings)
{
player.hp -= damage
break;
}

So one game developer trick is to have a budget and spread work out over time. This is very common practice in game development.

In this case, when you get a collision callback, queue it in a deque, and after the physics update, you process the the front of the deque until you reach your budget for that frame. Specify something really small, like 0.2 milliseconds. Then leave the rest for the next frame. Put an assert on the queue for max size, like 1000 so that if you are not keeping up with the queue, then you know you need to increase your budget.

Oh and I should add, that the reason for this is to keep frame rate steady, at the expense of a little latency.

1 Like