Velocity and Gravity in Flutter Games with Flame

Craig Oda
CodeCakes
Published in
2 min readApr 24, 2022
Flutter games with Flame 1.1.1

Leena is a new Flame beginner developer series that uses velocity, gravity, and friction to simulate the motions of a girl skateboarder.

leena.position += velocity * dt;

The position of the sprite character Leena is a vector with force in the X and Y space. The game is limited to 2D movements. Velocity is also a vector. The dt is the time difference between frames. In Flame, the difference is usually 1/60th of a second as the engine normally runs at 60fps.

velocity.y += gravity;

Gravity is a double, or floating point, number. The left-top of the game screen is 0, 0.

Adding a value to the Y axis makes the character move down.

Gravity is applied to velocity 60 times per second inside of a loop system built into Flame. The primary loop is called, update.

To simplify motion, focus on the Y axis first. In the code snippet, the size[1] is the height of the mobile app screen. As long as the player is above the bottom of the screen, the position is changed by velocity * time.

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

if (leena.y < size[1] - leena.height) {
velocity.y += gravity;
leena.position.y += velocity.y * dt;
}
}

I have a hundred free videos on learning basic programming by having fun building mobile app games with Flame.

--

--

Craig Oda
CodeCakes

open source advocate, writer, Flutter developer, father, husband, fly fisherman, surfer