When you dreamed of your game, you saw lot of tiles.
We are lucky; we decided at the beginning that only tiles will decide if a collision happens. In that way, the code of the robot doesn't need to be changed and we can add how many types of tiles as we want!
With 2 tiles examples, we will show how to add different types of tiles, to obtain this applet:
The robot can walk on this tile only if it comes from the top, otherwise it crosses it. We use an AnimatedSprite as action sprite of this wrapper to have a nice animation. In CrossTile.java wrapper, we override the method checkCollision(Sprite) to define if a collision happens or not:
Hint: To obtain the wave effect of sprites, you only need to increase the current picture of the AnimatedSprite.
Carousel tiles
This tile is more complicate than the previous one. When the robot arrives on the upper side of the tile, it is shifted to the right.
We have to explain different elements before to show the code:
The width of this sprite is one pixel greater than the other tiles. This is done because collisions are processed from the left to the right, and if the carousel tile is not in the cell beside it, it will receive the pre-collision event only when the robot is in the cell.
Because the carousel is one pixel greater than the other tiles, in checkCollision(Sprite) method, we have to ignore the first column of pixels in the left side of the sprite if the robot is not walking on the tile.
The id of the tile is the highest to receive pre-collision event before all other tiles.
When 2 carousel tiles are beside, the robot must be shifted only one time. Do to this feature, we store the robot in a static variable, and the first carousel tile, which can shift the robot, processes the action.
Now that we specified these details, we can show the code from CarouselTile.java:
.../** * Checks if the robot collides with the tile. */publicbooleancheckCollision(Spritesprite){return(super.checkCollision(sprite)&&(((sprite.getX()+sprite.getWidth()-sprite.getRightCollisionOffset())>(getX()+1))||((sprite.getY()+sprite.getHeight()-sprite.getBottomCollisionOffset())==getY())));}/** * Stores the robot to shift. */protectedbooleanpreCollisionWith(Sprites){colSprite=s;returnfalse;}/** * Shifts the robot. */publicvoidtick(intticks){super.tick(ticks);if((colSprite!=null)&&!((RobotControler)colSprite).isFlying()){colSprite.setPosition(colSprite.getX()+SPEED,colSprite.getY());}colSprite=null;}...