A smart way to manage sleeping objects with Box2D

If you followed Box2D: tutorial for the absolute beginners, then you know you can put some object to “sleep” to improve performance by not simulating inactive bodies.

This is CPU saving but can be used for some game concepts too.

Just think about Super Stacker, where you have happy and afraid bricks.

Super Stacker

If you spend some time on this game, you will find happy bricks are the inactive ones while the afraid ones are still falling/moving.

This can be achieved by playing on the IsSleeping status.

Let’s take the same script introduced in Box2D: tutorial for the absolute beginners and make some changes:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class demo extends Sprite {
		var the_world:b2World;
		var time_count:Timer=new Timer(3000);
		public function demo() {
			var environment:b2AABB=new b2AABB  ;
			environment.lowerBound.Set(-100.0,-100.0);
			environment.upperBound.Set(100.0,100.0);
			var gravity:b2Vec2=new b2Vec2(0.0,10.0);
			the_world=new b2World(environment,gravity,true);
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			the_body=new b2BodyDef  ;
			the_body.position.Set(8.5,14);
			the_box=new b2PolygonDef  ;
			the_box.SetAsBox(8.5,0.5);
			the_box.friction=0.3;
			the_box.density=0;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
			addEventListener(Event.ENTER_FRAME,on_enter_frame);
			time_count.addEventListener(TimerEvent.TIMER,on_time);
			time_count.start();
		}
		public function on_time(e:Event) {
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			var box_width=Math.random() + 0.1;
			var box_height=Math.random() + 0.1;
			the_body=new b2BodyDef;
			the_body.position.Set(Math.random() * 10 + 2,0);
			the_body.userData=new cubeface();
			the_body.userData.width=box_width * 60;
			the_body.userData.height=box_height * 60;
			the_box=new b2PolygonDef;
			the_box.SetAsBox(box_width,box_height);
			the_box.friction=0.3;
			the_box.density=1;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
			addChild(the_body.userData);
		}
		public function on_enter_frame(e:Event) {
			the_world.Step(1 / 30,10);
			for (var bb:b2Body=the_world.m_bodyList; bb; bb=bb.m_next) {
				if (bb.m_userData is Sprite) {
					bb.m_userData.x=bb.GetPosition().x * 30;
					bb.m_userData.y=bb.GetPosition().y * 30;
					bb.m_userData.rotation=bb.GetAngle() * 180 / Math.PI;
					if (bb.IsSleeping()) {
						bb.m_userData.gotoAndStop(2);
					}
					else {
						bb.m_userData.gotoAndStop(1);
					}
				}
			}
		}
	}
}

In the on_time function I added some lines to assign a cubeface object to the rectangle I create.

The cubeface object is just a MovieClip with two frames, one with an happy box and one with a sad one.

Line 43: Assigning the cubeface object to the rectangle

Lines 44-45: Defining movieclip width and height

Line 53: Adding the movieclip on the stage

Later, in the on_enter_frame function, you can find the classic Box2d function used to update sprites (or movieclips) position and rotation.

Lines 62-67: Checking if the body is sleeping with IsSleeping. If the body is sleeping, then stop the movieclip on frame 2 (the happy square), otherwise stop it on frame 1 (the afraid square).

This is the result

And this is the source code to download.

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