Skip to main content

Friction, density & restitution

We already know that bodies have different attributes. In this article, we will talk about friction, density, and restitution.

Density

The density is the mass per square meter. Higher density means heavier bodies, and it can't be negative: A bowling ball is very dense, yet a balloon isn’t very dense at all as it is mainly filled with air.

Friction

The friction comes to play when two bodies slide with each other: a block of ice would have very low friction, but a rubber ball would have high friction.

Restitution

Restitution determines how much a body will bounce after a collision: a rock would have very low restitution, but a basketball would have high restitution.

Let's code

Setting the friction, density, or restitution is done on the FixtureDef like this:

final fixtureDef = FixtureDef(shape)
..density = 10
..friction = .5
..restitution = .5;

Let's create an inclined floor and drop a box with different values for density, friction, and restitution, and let's see the result.

First, we create the class Box:

class Box extends BodyComponent {

Body createBody() {
final bodyDef = BodyDef(
position: Vector2(10, 0),
type: BodyType.dynamic,
);

final shape = PolygonShape()..setAsBoxXY(.25, .25);
final fixtureDef = FixtureDef(shape)
..density = 10
..friction = .5
..restitution = .5;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}

Then, we create the class Floor:

class Floor extends BodyComponent {

Body createBody() {
final bodyDef = BodyDef(
position: Vector2(0, worldSize.y - .75),
type: BodyType.static,
);

final shape = EdgeShape()..set(Vector2.zero(), Vector2(worldSize.x, -2));
final fixtureDef = FixtureDef(shape)..friction = .1;
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}

Now we add the Floor and the Box to the game:

class GameLesson03 extends MyGame {

Future<void> onLoad() async {
super.onLoad();
add(Floor());
add(Box());
}
}

We run the code, and this is the result:

Box bouncing

Box bouncing

Let's see what happens if we change the restitution value to 1 like this:

final fixtureDef = FixtureDef(shape)
..density = 10
..friction = .5
..restitution = 1;
Ball bouncing very high

Ball bouncing very high

Did you notice the difference? The box will bounce very high when the restitution value is 1. Now you can play with the density, friction, and restitution values to see different results.

Conclusion

In this article, we learned about density, friction, and restitution and how just changing the value of one of them can make a huge difference in the behavior of the bodies.

info

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