-
Notifications
You must be signed in to change notification settings - Fork 24
Collisions with Sprites
It can be useful to detect if 2 sprites collide, for example if a missile touches a space ship.
Collisions are computed using simplified shapes: CollisionCircle or CollisionRectangle. Note that for the moment rectangles cannot be rotated so don't use them with sprites that rotate.
You can define collision zone with custom types. For examples zones that kills (nose of the missile), and zones that are fragile (middle of the spaceship).
Note that collisions are static, which means they don't take the speed into account. If your missile is on the left of the spaceship in one frame, and on the right the frame just after, no collision will be detected.
// somewhere
public static final int KILL_TYPE = 1;
public static final int FRAGILE_TYPE = 2;
public class SpaceShip extends Sprite {
public SpaceShip(int width, int height) {
super(width, height);
// x%, y%, radius%
CollisionCircle collision = new CollisionCircle(this, 0.5f, 0.5f, 0.5f);
addCollision(FRAGILE_TYPE, collision);
}
}
public class Missile extends Sprite {
private CollisionCircle mCollision;
public Missile(int width, int height) {
super(width, height);
// x%, y%, radius%
mCollision = new CollisionCircle(this, 0.75f, 0.5f, 0.25f);
addCollision(KILL_TYPE, mCollision);
}
@Override
public void tick(OpenGLRenderer renderer) {
super.tick(renderer);
ArrayList<Collision> shipCollisions = mSpaceShip.getCollisions(FRAGILE_TYPE);
for(Collision collision : shipCollisions) {
if (collision.collide(mCollision)) {
mSpaceShip.killed();
break;
}
}
}
}
It is possible to see the collisions in a debug mode. Just call setDebugMode() on the smartGLRenderer.