Game Development Reference
In-Depth Information
This code adds a new method called testCollisions() that iterates through all
the game objects and tests whether there is a collision between the bunny head and
another game object. This particular test is subdivided into three separate methods
called onCollisionBunnyHeadWithRock() , onCollisionBunnyWithGoldCoin() ,
and onCollisionBunnyWithFeather() , which are still empty.
Next, fill in the onCollisionBunnyHeadWithRock() method with the
following code:
private void onCollisionBunnyHeadWithRock (Rock rock) {
BunnyHead bunnyHead = level.bunnyHead;
float heightDifference = Math.abs(bunnyHead.position.y
- ( rock.position.y + rock.bounds.height));
if (heightDifference > 0.25f) {
boolean hitRightEdge = bunnyHead.position.x > (
rock.position.x + rock.bounds.width / 2.0f);
if (hitRightEdge) {
bunnyHead.position.x = rock.position.x + rock.bounds.width;
} else {
bunnyHead.position.x = rock.position.x -
bunnyHead.bounds.width;
}
return;
}
switch (bunnyHead.jumpState) {
case GROUNDED:
break;
case FALLING:
case JUMP_FALLING:
bunnyHead.position.y = rock.position.y +
bunnyHead.bounds.height + bunnyHead.origin.y;
bunnyHead.jumpState = JUMP_STATE.GROUNDED;
break;
case JUMP_RISING:
bunnyHead.position.y = rock.position.y +
bunnyHead.bounds.height + bunnyHead.origin.y;
break;
}
}
This code handles collisions between the bunny head game object and a rock game
object and is called when a collision is detected. Then, the bunny head game object
is moved accordingly to prevent it from falling through our platforms—the rock
game objects.
 
Search WWH ::




Custom Search