/* This is where all game physics starts each frame. It is called each frame by the game statem manager after player input and AI have been processed. It updates the physical state of all dynamic objects in the game and moves all objects to their end of frame positions, updates all necessary object velocities, and calls all collision event handlers. */ void Physics::update(Game *game) { // WE'LL USE A CONTINUOUS COLLISION SYSTEM TO ENSURE TEMPORAL // COHERENCE, WHICH MEANS WE'LL MAKE SURE COLLISIONS ARE RESOLVED // IN THE ORDER WITH WHICH THEY HAPPEN. WE DON'T WANT GAME EVENTS // TO APPEAR TO HAPPEN IN THE WRONG ORDER. WE'LL TRY TO MAKE IT // A LITTLE MORE EFFICIENT BY EMPLOYING A VARIATION ON THE // SWEEP AND PRUNE ALGORITHM FOR DYNAMIC-DYNAMIC OBJECT COLLISIONS // IN CASE WE'RE DOING THE ONE UPDATE STEP AT A TIME // THIS MAKES SURE THE UPDATE DOESN'T GET CALLED AGAIN // NEXT FRAME WITHOUT THE USER EXPLICITY REQUESTING IT // BY PRESSING THE 'T' KEY (for Time sTep) activatedForSingleUpdate = false; // WE'LL NEED THE WORLD TO ACCESS THE SPRITES AND WORLD LAYERS GameStateManager *gsm = game->getGSM(); World *world = gsm->getWorld(); // NOTE THAT WE MAKE SURE THE activeCollisions VECTOR IS // EMPTIED BEFORE THIS METHOD EXITS, SO WE CAN ASSUME // IT'S EMPTY NOW. activeCollisions CONTAINS ALL THE COLLISIONS // DETECTED SO FAR THIS FRAME. THESE ARE THE THINGS WE MUST // RESOLVE. // START THE CLOCK AT 0, THAT MEANS 0% OF THE WAY THROUGH THE FRAME. // NOTE THAT TIME 0 IS THE MOST DANGEROUS TIME FOR DETECTING COLLISIONS // BECAUSE THEY CAN BE EASILY OVERLOOKED. THE SAME FOR SIMULTANEOUS // COLLISIONS. TO MINIMIZE RIGID BODY PENETRATION, SUCH CIRCUMSTANCES // ARE TYPICALLY HANDLED AS SPECIAL CASES currentCollisionTime = 0.0f; // FIRST WE NEED TO DO COLLISION TESTING PREP WORK FOR SPRITES // APPLY ACCELERATION AND GRAVITY TO VELOCITY // INIT TILE COLLISION INFO // SET ON TILE LAST FRAME USING ON TILE THIS FRAME // SET ON TILE THIS FRAME TO FALSE // GET COLLISIONS WITH ALL TILES TO HAPPEN DURING THIS FRAME // PUT THESE COLLISIONS INTO A SORTABLE DATA STRUCTURE // INIT SPRITE'S SWEPT SHAPE INFO // FOR ALL SPRITES, INCLUDING THE BOTS AND PLAYER vector<CollidableObject*>::iterator spritesIt = sortedSweptShapes[LEFT_EDGE]->begin(); while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end()) { CollidableObject *sprite = (*spritesIt); prepSpriteForCollisionTesting(world, sprite); getAllTileCollisionsForAGivenSprite(world, sprite, 1.0f); spritesIt++; } // PREPARE FOR SPRITE-SPRITE COLLISION TESTING // SWEEP AND PRUNE DATA STRUCTURES PREP WORK // SORT S_AND_P VECTOR SORTED BY START X OF SWEPT SHAPE // SORT S_AND_P VECTOR SORTED BY END X OF SWEPT SHAPE // WE DON'T NEED THE Y-AXIS SORTED, BUT WOULD IF THIS // WERE A 3D SYSTEM TO SAVE ON COMPARISONS. // WE'RE USING C++'s STL sort METHOD AND ARE PROVIDING // A CUSTOM MEANS FOR COMPARISON sort(sortedSweptShapes[LEFT_EDGE]->begin(), sortedSweptShapes[LEFT_EDGE]->end(), SweptShapesComparitorByLeft()); sort(sortedSweptShapes[RIGHT_EDGE]->begin(), sortedSweptShapes[RIGHT_EDGE]->end(), SweptShapesComparitorByRight()); // RECORD SORTED POSITIONS WITH EACH SPRITE. THEY NEED TO KNOW WHERE // THEY ARE IN THOSE DATA STRUCTURES SUCH THAT WE CAN JUMP INTO // THOSE DATA STRUCTURES TO TEST COLLISIONS WITH NEIGHBORS updateSweptShapeIndices(); // YOU'LL NEED TO TEST FOR SPRITE-TO-SPRITE COLLISIONS HERE // *** LOOP STARTS HERE. WE'LL DO THIS UNTIL THERE ARE NO // MORE COLLISIONS TO RESOLVE FOR THIS FRAME while (activeCollisions.size() > 0) { // SORT COLLISION OBJECTS BY TIME OF COLLISION // NOTE THAT I'M JUST EMPLOYING THE STL'S List // CLASS' SORT METHOD BY PROVIDING MY OWN // MEANS FOR COMPARING Collision OBJECTS activeCollisions.sort(CollisionComparitor()); // GET FIRST COLLISION - NOTE THAT WE HAVE THE COLLISIONS SORTED // IN DESCENDING ORDER, SO TO TAKE THE EARLIEST ONE, WE REMOVE IT // FOM THE BACK OF THE SORTED LIST Collision *earliestCollision = activeCollisions.back(); activeCollisions.pop_back(); float collisionTime = earliestCollision->getTimeOfCollision(); // MOVE ALL SPRITES UP TO TIME OF FIRST COLLISION USING // APPROPRIATELY SCALED VELOCITIES moveAllSpritesUpToBufferedTimeOfCollision(earliestCollision); // AND ADVANCE COLLISION TIME currentCollisionTime = collisionTime; // AND UPDATE THE VELOCITIES OF THE SPRITE(S) INVOLVED IN THE COLLISION performCollisionResponse(earliestCollision); // EXECUTE COLLISION EVENT CODE // TEST TO SEE TYPES OF OBJECTS AND APPROPRIATE RESPONSE // ACCORDING TO CUSTOMIZED COLLISION EVENT HANDLER collisionListener->respondToCollision(game, earliestCollision); // FOR THE TWO OBJECTS INVOLVED IN THE COLLISION // REMOVE ALL OTHER COLLISIONS INVOLVING THEM // SINCE THEY ARE NOW OBSOLETE. THE REASON BEING // THE OBJECT COLLISION NOW LIKELY HAS A // DIFFERENT VECTOR // UPDATE THEIR SWEPT SHAPES // TEST THEM AGAINST TILES AGAIN CollidableObject *co1 = earliestCollision->getCO1(); CollidableObject *co2 = earliestCollision->getCO2(); removeActiveCOCollisions(co1); co1->updateSweptShape(1.0f - currentCollisionTime); getAllTileCollisionsForAGivenSprite(world, co1, 1.0f - currentCollisionTime); // ONLY DO IT FOR THE SECOND ONE IF IT'S NOT A TILE if (!earliestCollision->isCollisionWithTile()) { removeActiveCOCollisions(co2); co2->updateSweptShape(1.0f - currentCollisionTime); getAllTileCollisionsForAGivenSprite(world, co2, 1.0f - currentCollisionTime); } else { spriteToTileCollisionsThisFrame[co1].insert(earliestCollision->getTile()); recycledCollidableObjectsList.push_back(co2); } // NOW WE NEED TO SEE IF THE SPRITES INVOLVED IN THE JUST // RESOLVED COLLISION ARE GOING TO BE INVOLVED IN ANY MORE // WITH OTHER SPRITES BUT WE DON'T WANT TO CHECK ALL OF THEM, // WE ONLY WANT TO CHECK NEIGHBORS, BUT FIRST WE HAVE TO // MAKE SURE THE SPRITE(S) THAT WE JUST RESOLVED ARE IN THEIR // PROPER SWEPT SHAPE LOCATIONS WITHOUT HAVING TO RESORT EVERTYHING // IF IT WAS ONLY ONE SPRITE WITH A TILE THIS IS EASY TO DO if (earliestCollision->isCollisionWithTile()) { reorderCollidableObject(co1); } // YOU'LL HAVE TO WORRY ABOUT REORDERING STUFF FOR COLLISIONS // BETWEEN TWO SPRITES // NOW TEST NEIGHBORS OF SPRITES INVOLVED IN RESOLVED COLLISION // AGAINST NEIGHBORS IN SWEPT SHAPE DATA STRUCTURES. YOU'LL HAVE // TO FIGURE OUT HOW TO DO THIS AND HOW TO RESOLVE SUCH COLLISIONS // RECYCLE THE COLLISION SINCE WE'RE NOW DONE WITH IT recycledCollisions.push_back(earliestCollision); } // APPLY THE REMAINING TIME TO MOVE THE SPRITES. NOTE THAT // THIS IS ACTUALLY A VERY RISKY, TRICKY STEP BECAUSE IT COULD // MOVE OBJECTS ALMOST TO THE POINT OF COLLISION, WHICH MAY THEN // BE DETECTED ALMOST AT TIME 0 NEXT FRAME. THERE ARE OTHER TRICKY // ISSUES RELATED TO OUR BUFFER AS WELL, SO WE CHEAT A LITTLE HERE // AND SCALE THE TIME REMAINING DOWN A LITTE if (currentCollisionTime < 1.0f) moveAllSpritesToEndOfFrame(); // INIT TILE COLLISION INFO // SET ON TILE LAST FRAME USING ON TILE THIS FRAME // SET ON TILE THIS FRAME TO FALSE spritesIt = sortedSweptShapes[LEFT_EDGE]->begin(); while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end()) { CollidableObject *sprite = (*spritesIt); sprite->advanceOnTileStatus(); spritesIt++; } // WE'RE NOT GOING TO ALLOW MULTIPLE COLLISIONS TO HAPPEN IN A FRAME // BETWEEN THE SAME TWO OBJECTS spriteToTileCollisionsThisFrame.clear(); }
/* This is where all game physics starts each frame. It is called each frame by the game statem manager after player input and AI have been processed. It updates the physical state of all dynamic objects in the game and moves all objects to their end of frame positions, updates all necessary object velocities, and calls all collision event handlers. */ void Physics::update(Game *game) { // WE'LL USE A CONTINUOUS COLLISION SYSTEM TO ENSURE TEMPORAL // COHERENCE, WHICH MEANS WE'LL MAKE SURE COLLISIONS ARE RESOLVED // IN THE ORDER WITH WHICH THEY HAPPEN. WE DON'T WANT GAME EVENTS // TO APPEAR TO HAPPEN IN THE WRONG ORDER. WE'LL TRY TO MAKE IT // A LITTLE MORE EFFICIENT BY EMPLOYING A VARIATION ON THE // SWEEP AND PRUNE ALGORITHM FOR DYNAMIC-DYNAMIC OBJECT COLLISIONS // IN CASE WE'RE DOING THE ONE UPDATE STEP AT A TIME // THIS MAKES SURE THE UPDATE DOESN'T GET CALLED AGAIN // NEXT FRAME WITHOUT THE USER EXPLICITY REQUESTING IT // BY PRESSING THE 'T' KEY (for Time sTep) activatedForSingleUpdate = false; // WE'LL NEED THE WORLD TO ACCESS THE SPRITES AND WORLD LAYERS GameStateManager *gsm = game->getGSM(); World *world = gsm->getWorld(); // NOTE THAT WE MAKE SURE THE activeCollisions VECTOR IS // EMPTIED BEFORE THIS METHOD EXITS, SO WE CAN ASSUME // IT'S EMPTY NOW. activeCollisions CONTAINS ALL THE COLLISIONS // EMPTIED BEFORE THIS METHOD EXITS, SO WE CAN ASSUME // IT'S EMPTY NOW. activeCollisions CONTAINS ALL THE COLLISIONS // DETECTED SO FAR THIS FRAME. THESE ARE THE THINGS WE MUST // RESOLVE. // START THE CLOCK AT 0, THAT MEANS 0% OF THE WAY THROUGH THE FRAME. // NOTE THAT TIME 0 IS THE MOST DANGEROUS TIME FOR DETECTING COLLISIONS // BECAUSE THEY CAN BE EASILY OVERLOOKED. THE SAME FOR SIMULTANEOUS // COLLISIONS. TO MINIMIZE RIGID BODY PENETRATION, SUCH CIRCUMSTANCES // ARE TYPICALLY HANDLED AS SPECIAL CASES currentCollisionTime = 0.0f; // FIRST WE NEED TO DO COLLISION TESTING PREP WORK FOR SPRITES // APPLY ACCELERATION AND GRAVITY TO VELOCITY // INIT TILE COLLISION INFO // SET ON TILE LAST FRAME USING ON TILE THIS FRAME // SET ON TILE THIS FRAME TO FALSE // GET COLLISIONS WITH ALL TILES TO HAPPEN DURING THIS FRAME // PUT THESE COLLISIONS INTO A SORTABLE DATA STRUCTURE // INIT SPRITE'S SWEPT SHAPE INFO // FOR ALL SPRITES, INCLUDING THE BOTS AND PLAYER vector<CollidableObject*>::iterator spritesIt = sortedSweptShapes[LEFT_EDGE]->begin(); while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end()) { CollidableObject *sprite = (*spritesIt); prepSpriteForCollisionTesting(world, sprite); getAllTileCollisionsForAGivenSprite(world, sprite, 1.0f); spritesIt++; } // PREPARE FOR SPRITE-SPRITE COLLISION TESTING // SWEEP AND PRUNE DATA STRUCTURES PREP WORK // SORT S_AND_P VECTOR SORTED BY START X OF SWEPT SHAPE // SORT S_AND_P VECTOR SORTED BY END X OF SWEPT SHAPE // WE DON'T NEED THE Y-AXIS SORTED, BUT WOULD IF THIS // WERE A 3D SYSTEM TO SAVE ON COMPARISONS. // WE'RE USING C++'s STL sort METHOD AND ARE PROVIDING // A CUSTOM MEANS FOR COMPARISON sort(sortedSweptShapes[LEFT_EDGE]->begin(), sortedSweptShapes[LEFT_EDGE]->end(), SweptShapesComparitorByLeft()); sort(sortedSweptShapes[RIGHT_EDGE]->begin(), sortedSweptShapes[RIGHT_EDGE]->end(), SweptShapesComparitorByRight()); // RECORD SORTED POSITIONS WITH EACH SPRITE. THEY NEED TO KNOW WHERE // THEY ARE IN THOSE DATA STRUCTURES SUCH THAT WE CAN JUMP INTO // THOSE DATA STRUCTURES TO TEST COLLISIONS WITH NEIGHBORS updateSweptShapeIndices(); // YOU'LL NEED TO TEST FOR SPRITE-TO-SPRITE COLLISIONS HERE // *** LOOP STARTS HERE. WE'LL DO THIS UNTIL THERE ARE NO // MORE COLLISIONS TO RESOLVE FOR THIS FRAME while (activeCollisions.size() > 0) { // SORT COLLISION OBJECTS BY TIME OF COLLISION // NOTE THAT I'M JUST EMPLOYING THE STL'S List // CLASS' SORT METHOD BY PROVIDING MY OWN // MEANS FOR COMPARING Collision OBJECTS activeCollisions.sort(CollisionComparitor()); // GET FIRST COLLISION - NOTE THAT WE HAVE THE COLLISIONS SORTED // IN DESCENDING ORDER, SO TO TAKE THE EARLIEST ONE, WE REMOVE IT // FOM THE BACK OF THE SORTED LIST Collision *earliestCollision = activeCollisions.back(); activeCollisions.pop_back(); float collisionTime = earliestCollision->getTimeOfCollision(); // MOVE ALL SPRITES UP TO TIME OF FIRST COLLISION USING // APPROPRIATELY SCALED VELOCITIES moveAllSpritesUpToBufferedTimeOfCollision(earliestCollision); // AND ADVANCE COLLISION TIME currentCollisionTime = collisionTime; // AND UPDATE THE VELOCITIES OF THE SPRITE(S) INVOLVED IN THE COLLISION performCollisionResponse(earliestCollision); // EXECUTE COLLISION EVENT CODE // TEST TO SEE TYPES OF OBJECTS AND APPROPRIATE RESPONSE // ACCORDING TO CUSTOMIZED COLLISION EVENT HANDLER collisionListener->respondToCollision(game, earliestCollision); // FOR THE TWO OBJECTS INVOLVED IN THE COLLISION // REMOVE ALL OTHER COLLISIONS INVOLVING THEM // SINCE THEY ARE NOW OBSOLETE. THE REASON BEING // THE OBJECT COLLISION NOW LIKELY HAS A // DIFFERENT VECTOR // UPDATE THEIR SWEPT SHAPES // TEST THEM AGAINST TILES AGAIN CollidableObject *co1 = earliestCollision->getCO1(); CollidableObject *co2 = earliestCollision->getCO2(); removeActiveCOCollisions(co1); co1->updateSweptShape(1.0f - currentCollisionTime); getAllTileCollisionsForAGivenSprite(world, co1, 1.0f - currentCollisionTime); // ONLY DO IT FOR THE SECOND ONE IF IT'S NOT A TILE if (!earliestCollision->isCollisionWithTile()) { removeActiveCOCollisions(co2); co2->updateSweptShape(1.0f - currentCollisionTime); getAllTileCollisionsForAGivenSprite(world, co2, 1.0f - currentCollisionTime); } else { spriteToTileCollisionsThisFrame[co1].insert(earliestCollision->getTile()); recycledCollidableObjectsList.push_back(co2); } // NOW WE NEED TO SEE IF THE SPRITES INVOLVED IN THE JUST // RESOLVED COLLISION ARE GOING TO BE INVOLVED IN ANY MORE // WITH OTHER SPRITES BUT WE DON'T WANT TO CHECK ALL OF THEM, // WE ONLY WANT TO CHECK NEIGHBORS, BUT FIRST WE HAVE TO // MAKE SURE THE SPRITE(S) THAT WE JUST RESOLVED ARE IN THEIR // PROPER SWEPT SHAPE LOCATIONS WITHOUT HAVING TO RESORT EVERTYHING // IF IT WAS ONLY ONE SPRITE WITH A TILE THIS IS EASY TO DO if (earliestCollision->isCollisionWithTile()) { reorderCollidableObject(co1); } // YOU'LL HAVE TO WORRY ABOUT REORDERING STUFF FOR COLLISIONS // BETWEEN TWO SPRITES // NOW TEST NEIGHBORS OF SPRITES INVOLVED IN RESOLVED COLLISION // AGAINST NEIGHBORS IN SWEPT SHAPE DATA STRUCTURES. YOU'LL HAVE // TO FIGURE OUT HOW TO DO THIS AND HOW TO RESOLVE SUCH COLLISIONS // RECYCLE THE COLLISION SINCE WE'RE NOW DONE WITH IT recycledCollisions.push_back(earliestCollision); } // APPLY THE REMAINING TIME TO MOVE THE SPRITES. NOTE THAT // THIS IS ACTUALLY A VERY RISKY, TRICKY STEP BECAUSE IT COULD // MOVE OBJECTS ALMOST TO THE POINT OF COLLISION, WHICH MAY THEN // BE DETECTED ALMOST AT TIME 0 NEXT FRAME. THERE ARE OTHER TRICKY // ISSUES RELATED TO OUR BUFFER AS WELL, SO WE CHEAT A LITTLE HERE // AND SCALE THE TIME REMAINING DOWN A LITTE if (currentCollisionTime < 1.0f) moveAllSpritesToEndOfFrame(); // INIT TILE COLLISION INFO // SET ON TILE LAST FRAME USING ON TILE THIS FRAME // SET ON TILE THIS FRAME TO FALSE spritesIt = sortedSweptShapes[LEFT_EDGE]->begin(); while (spritesIt != sortedSweptShapes[LEFT_EDGE]->end()) { CollidableObject *sprite = (*spritesIt); sprite->advanceOnTileStatus(); spritesIt++; } // while(!colliding){ for (b2Contact* contact = game->getbworld()->GetContactList(); contact; contact = contact->GetNext()) { b2Body* a = contact->GetFixtureA()->GetBody(); b2Body* b = contact->GetFixtureB()->GetBody(); AnimatedSprite* c = (AnimatedSprite*) a->GetUserData(); AnimatedSprite* d = (AnimatedSprite*) b->GetUserData(); unsigned int x = c->getSpriteType()->getSpriteTypeID(); unsigned int y = d->getSpriteType()->getSpriteTypeID(); switch(x){ case 0: // player break; case 1: // break; case 2: GarbageMon *e; e= (GarbageMon*)c; //co.remove(e); //game->getbworld()->DestroyBody(e->getBody()); //e->collisionResponse(game); break; case 4: //Trash *f = (Trash*)c; //f->collisionResponse(game); break; } switch(y){ // if (x == 0) { case 0: // player break; case 1: // break; case 2: // colliding = true; GarbageMon *g; g= (GarbageMon*)d; co.push_back(g); co.remove(g); //g->setCurrentState(L"DYING"); g->getPhysicalProperties()->setPosition(9999.9f, 9999.9f); game->playExplosion(); //wstring s = c->getCurrentState(); g->getBody()->ApplyLinearImpulse(b2Vec2(99999.9f, 0.0f), g->getBody()->GetPosition(), true); //game->getbworld()->DestroyBody(g->getBody()); //g->getBody()->DestroyFixture(g->getBody()->GetFixtureList()); //g->getBody()->GetWorld()->DestroyBody(g->getBody()); g->collisionResponse(game); //colliding = false; break; case 5: Trash *h = (Trash*)d; co.remove(h); //h->collisionResponse(game); break; } } //} //} //update sprites according to box2d thingies list<CollidableObject*>::iterator i = co.begin(); while (i != co.end()) { CollidableObject* c = *i; PhysicalProperties* p = c->getPhysicalProperties(); p->setX(c->getBody()->GetPosition().x * pikachu); p->setY(c->getBody()->GetPosition().y * pikachu); i++; } float32 time = 1.0f/1.25f; int32 vel = 8; int32 pos = 3; game->getbworld()->Step (time, vel, pos); for (b2Contact* contact = game->getbworld()->GetContactList(); contact; contact = contact->GetNext()) { b2Fixture* a = contact->GetFixtureA(); b2Fixture* b = contact->GetFixtureB(); AnimatedSprite* a2 = (AnimatedSprite*) a->GetBody()->GetUserData(); AnimatedSprite* b2 = (AnimatedSprite*) b->GetBody()->GetUserData(); if(a2->getSpriteType()->getSpriteTypeID() == 0 && b2->getSpriteType()->getSpriteTypeID() == 2){ b->GetBody()->ApplyLinearImpulse(a->GetBody()->GetWorldVector(b2Vec2(0,-2)), b->GetBody()->GetPosition(), true); b->GetBody()->SetLinearVelocity(b2Vec2 (0,0)); SpriteManager *sm = game->getGSM()->getSpriteManager(); int health = (int) _wtoi(sm->getHealthBar()->getCurrentState().c_str()); if (health <= 10){ // WHEN PLAYER RUNS OUT OF HEALTH, SKIP TO NEXT DAY // PENALTY LIES IN THE PLAYER NOT ACHIEVING THE DAY'S GOALS // AND HAVE TO SUFFER INCREASE IN POLLUTION BAR sm->getHealthBar()->setCurrentState(to_wstring(100)); } else{ //OutputDebugStringW(L"HI"); sm->getHealthBar()->setCurrentState(to_wstring(health - 10)); } } //contact->GetFixtureB()->GetBody()->DestroyFixture(a); } // WE'RE NOT GOING TO ALLOW MULTIPLE COLLISIONS TO HAPPEN IN A FRAME // BETWEEN THE SAME TWO OBJECTS spriteToTileCollisionsThisFrame.clear(); }