public boolean testCollision(Sprite testSprite) { // Check for collision with // another sprite if (testSprite != this) { return spaceOccupied.intersects(testSprite.getSpaceOccupied()); } // end if return false; } // end testCollision
public void update() { Sprite sprite; // Iterate through sprite list for (int cnt = 0; cnt < size(); cnt++) { sprite = (Sprite) elementAt(cnt); // Update a sprite's position sprite.updatePosition(); // Test for collision. Positive // result indicates a collision int hitIndex = testForCollision(sprite); if (hitIndex >= 0) { // a collision has occurred bounceOffSprite(cnt, hitIndex); } // end if } // end for loop } // end update
private void bounceOffSprite(int oneHitIndex, int otherHitIndex) { // Swap motion vectors for // bounce algorithm Sprite oneSprite = (Sprite) elementAt(oneHitIndex); Sprite otherSprite = (Sprite) elementAt(otherHitIndex); Point swap = oneSprite.getMotionVector(); oneSprite.setMotionVector(otherSprite.getMotionVector()); otherSprite.setMotionVector(swap); } // end bounceOffSprite()
private int testForCollision(Sprite testSprite) { // Check for collision with other // sprites Sprite sprite; for (int cnt = 0; cnt < size(); cnt++) { sprite = (Sprite) elementAt(cnt); if (sprite == testSprite) // don't check self continue; // Invoke testCollision method // of Sprite class to perform // the actual test. if (testSprite.testCollision(sprite)) // Return index of colliding // sprite return cnt; } // end for loop return -1; // No collision detected } // end testForCollision()