You noticed in the previous chapter how long the robot must walk on a tile before it falls. Its legs are in the empty space, and it doesn't fall. Now it is time to introduce collision offsets.
Collision offsets are four variables to set in a sprite. By default, they are set to 0. Some times, it is useful to chance their values, like in our case.
This picture shows how offsets are disposed in a sprite. You can change their value with the following methods of the sprites object:
In our example, we only need to change the left and the right offsets, as show in the following picture:
6 pixels for the left collision offset
8 pixels for the right collision offset
This is done in the class DisplayRobotFinal.java.
But, we have to change something else. In the DummyRobot object, when we change the position of the new sprite, we need to consider collision offsets. In DummyRobotFinal.java, needed changes are done in changeDirection(RobotSprite, RobotSprite) method:
.../** * Changes direction of the robot */protectedvoidchangeDirection(RobotSpritefromSprite,RobotSpritetoSprite){PlayFieldparent=getParent();SpritefinalWrapper=getFinalWrapper();Pointp=getPosition();toSprite.setCurrentPictureNumber(fromSprite.getCurrentPictureNumber());parent.removeSprite(finalWrapper);setActionSprite(toSprite);setPosition(p.x+(fromSprite.getLeftCollisionOffset()-toSprite.getLeftCollisionOffset()),p.y);toSprite.fly(fromSprite.isFlying());parent.addSprite(finalWrapper);}...
Finally, we assemble all of these elements to obtain this applet: