Box2D: tutorial for the absolute beginners – step 2

After understanding the meaning of the first lines in Box2D: tutorial for the absolute beginners, it’s time to explain the rest of the script.

Lines 19-27: These lines handle the debug draw. Remember Box2D does not draw anything, it just calculates position, rotation and motion of every object in the world. So it’s up to you to attach real graphic assets to worl objects. Anyway, with some lines you can enable a debug draw mode that will help you during the creation of your script. For more information about debug draw read Understanding Box2D debug draw.

Line 28 declaring final_body, b2Body type. b2Body is the object used to represent one rigid body. A rigid body is a chunk of matter that is so strong that the distance between any two bits of matter on the chunk is completely constant. They are hard like a diamond. Box2D only handles rigid bodies.

Line 29 and 31 declare and create the_body variable, b2BodyDef type. b2BodyDef handles the body definition. With the body definition we can specify the initial position of the body.

Line 30 and 33 declare and create the_box variable, b2PolygonDef type. b2PolygonDef is a polygon definition.

Line 32: setting the initial position of the body. Remember values are in meters and refer to the center of the body.

Line 34: SetAsBox function takes the_box and turns it into a box, passing the half-width and half-height as parameters. Read carefully… half-width and half-height. In meters.

Line 35: defining the friction of the box

Line 36: defining the density of the box. Setting the density of a body to zero, like in this case, will make the body static. A static body is not affected by gravity, collisions and so on. It’s just fixed in the stage. This will represent the ground.

Line 37: CreateBody creates the body previously defined

Line 38: I am creating the polygon shape previously defined with CreateShape on the body previously created with CreateBody

Line 39: Once the shape is attached, we instruct the body to compute its mass properties from the attached shapes using the method SetMassFromShapes. This is when the objects really exists.

Lines 40-42: Adding some listeners

Lines 45-58: This function, to be executed at every second, creates a box in the same way I created the ground, with the only exception at line 54 I am setting a density different than zero, meaning the body is not a static one. Every body with a density will react to collisions, gravity, forces and so on.

Lines 60: We must update the world at every frame. We can do it with Step function. Step has two parameters: the first is the time interval, in seconds. It means at every frame I am going to update the world as if 1/30s passed. The second is the constraint solver. The constraint solver solves all the constraints in the simulation, one at a time. A single constraint can be solved perfectly. However, when we solve one constraint, we slightly disrupt other constraints. To get a good solution, we need to iterate over all constraints a number of times. The suggested iteration count for Box2D is 10.

And now the entire script has been explained.

If you manage to turn this script into something interesting, send me at once and I’ll publish it on the blog.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers