To find out if an object has collided with another you can use the method that is present in all classes.
//Returns true if there was a collision, otherwise, returns false.
public boolean collided(GameObject);
Also, it is possible to check if there was a collision by using the static class Collision, with the method
boolean collided(GameObject obj1, GameObject obj2);
Example:
if( Collision.collided(barcoAmarelo, barcoVermelho) == true)
print("collided");
The collision class can be used to check collision between
any of the objects: GameObject, GameImage, Animation and Sprite.
Example: Checking for collisions between objects.
package Collision001;
import jplay.Animation;
import jplay.GameImage;
import jplay.Window;
import jplay.Sprite;
/**
* @author Gefersom Cardoso Lima
* Federal Fluminense University
* Computer Science
*/
public class Colision001
{
//At the time the bird colliding with the rock it explodes
public static void main(String[] args)
{
Window window = new Window(800,600);
GameImage stone = new GameImage("stone.png");
stone.x = 396;
stone.y = 63;
GameImage sky = new GameImage("sky.png");
Sprite bird = new Sprite("bird.png", 3);
bird.setTotalDuration(360);
Animation explosion = new Animation("explosion.png",20);
explosion.setTotalDuration(1400);
explosion.setLoop(false);//The animation will run only once.
bird.x = 100;
bird.y = 460;
boolean collided = false;
while(true)
{
sky.draw();
stone.draw();
if (collided == false)
{
bird.draw();
bird.update();
bird.moveTo(600, bird.y, 0.8);
if (bird.collided(stone))
{
collided = true;
System.out.println(explosion.width);
explosion.x = bird.x - 70;
explosion.y = bird.y - 50;
}
}
else
{
explosion.update();
explosion.draw();
}
if (explosion.isPlaying() == false && collided == true)
explosion.hide();
window.update();
window.delay(10);
}
}
}