Saltar al contenido principal

Collisions

In this article, we will learn about collisions. When coding a game, we want to know when objects collide with each other, so we can act accordingly. For example, when we throw a bird into a bunch of pigs, we may want to remove those pigs from the game.

Forge2D has a collision system that provides information about the objects involved in the collision. For our current use case, we just want to check what type the objects are, and if they are the same, we remove them from the game.

Let's take the source code from the previous article and make some modifications. Each time a ball hits a ball or a box hits a box, they will explode and be removed from the game.

We create an enum ObjectState to keep track of the current state:

enum ObjectState {
normal,
explode,
}

Let's update the Ball class and add a property to keep track of the state:

ObjectState state = ObjectState.normal;

We also have to override the function update(). If the state is explode, we need to delete the body and remove the ball from the game.

  
void update(double dt) {
super.update(dt);

if (state == ObjectState.explode) {
world.destroyBody(body);
gameRef.remove(this);
}
}

We create a function hit() that we will call each time a ball hits a ball:

  void hit() {

if (state == ObjectState.normal) {
state = ObjectState.explode;
}
}

Now we have to use the ContactCallbacks class as a mixin. This will allow us to detect collisions:

class Ball extends BodyComponent with ContactCallbacks

We override the function beginContact and check if the ball started contact with another ball. If yes, we call the function hit():


void beginContact(Object other, Contact contact) {
if (other is Ball) {
hit();
}
}

There is one more change we must do and is storing the body component into the body definition userData like this:

final bodyDef = BodyDef(
userData: this,
// More code...
);

As a practice, you can do the modifications to the Box class, and after it's done, running the code will give the following result:

Objects removed when they collide

Objects removed when they collide

Notice that when two objects of the same type collide, they will be removed from the game, and the body count will decrease.

info

You can try the live demo in your browser and get the source code of all tutorials from GitHub