![]() |
|
API >> Tutorials >> Fundamentals >> Sprite collisions
Sprite collisionsBut what about collisions between sprites? We saw in the previous example collisions with borders; here we will make a new wrapper which treats collisions between 2 balls.What this new wrapper will do: when a ball will touch another one, the animation of these 2 balls will change and when one cycle of this new animation will end, sprites will be removed from the playfield. To launch this new example, we need to adapt the previous example; the complete code is in CollisionSprites.java. Here's an applet running the CollisionSprites program:
The important line which changes is:
Of course, a new image is needed for the explosion, here it is:
The new wrapper is inserted between the moving wrapper and the animated sprite. Be careful with the order of wrappers, sometime it is important, especially for collisions. But here, it does not matter.
This wrapper is specially designed for animated sprites, that's why in the constructor we ask for an AnimatedSprite object. Elements of the new animation, after the collision, are passed as arguments. We save them in variables of the class, and we will use them during the collision. Note: We have to cast the actionSprite because the polymorphism is static, and therefore, it does not know dynamically that the actionSprite is an AnimatedSprite. Note: The method collisionWith(Sprite) is called for the two concerned sprites. It can be interesting to do different actions if sprites have not the same type; for example a ball and a brick, a ball has to bounce on a brick, and a brick has to disappear when the ball touchs it. Note: Once again, you can override the method checkCollision(Sprite) and have a more precise estimation of the collision. Finally, at the end of the new animation, the sprite has to be removed. In the AnimatedSprite, the method isSequenceEnded() tells us if a sequence of pictures has reach the end. We override the method tick(int) and we check this.
We use this method because it is called for each tick, and it is the only way for a wrapper to know if an animation ended.
Another solution could be to subclass AnimatedSprite and to override the method sequenceEnded() which is called at the end of the animation. But don't forget that a sprite is only for visual effects, and a wrapper for actions, but if you are an Ugly Duckling, you will mix graphics and actions. Now it is in your hands, have fun.
API >> Tutorials >> Fundamentals >> Sprite collisions
|