Creation of a rotating room with Flash and Box2D

I was thinking about a game concept which features physics and a rotating room, so I asked to myself how to make a rotating room with Box2D, and what is the best way to do it.

These are the three ways I tried.

1 – “Manually” rotating a static room

In my first attempt I built a static room with a compound object (see the theory of compound objects in this post), then I rotated the object at every frame.

This is the source code:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.Joints.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,10),true);
		private var worldScale:Number=30;
		private var container:b2Body;
		private var containerRotation:Number=0;
		private var containerStep:Number=Math.PI/1000;
		public function Main() {
			debugDraw();
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0.5;
			fixtureDef.density=1
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(240/worldScale,240/worldScale);
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,-234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(-234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);			
			for (var i:Number=0; i<12; i++) {
				addBox(Math.random()*300+50,Math.random()*300+50,38,38,true);
			}
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addBox(pX:Number,pY:Number,w:Number,h:Number,d:Boolean):void {
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			polygonShape.SetAsBox(w/worldScale/2,h/worldScale/2);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=1;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=polygonShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			if (d) {
				bodyDef.type=b2Body.b2_dynamicBody;
			}
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		private function debugDraw():void {
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function update(e:Event):void {
			containerRotation-=containerStep
			var mat22:b2Mat22=new b2Mat22();
			mat22.Set(containerRotation)
			var boxTransform:b2Transform=new b2Transform(container.GetPosition(),mat22);
			container.SetTransform(boxTransform);
			world.Step(1/30, 10, 10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

Lines 18-36: create the static room object

Lines 37-39: add some stuff

Lines 69-73: rotate the room object using SetTransform method

This is the result:

I did not like it because sometimes the stuff inside the room sleeps and messes up everything. Also, too much hassle with radians, b2Mat22 types, and positions.

2 - Pinning the room to a static body with a revolute joint

In this example the room is a dynamic object pinned to a static body (a sphere) with a revolute joint, which also has a motor

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.Joints.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,10),true);
		private var worldScale:Number=30;
		public function Main() {
			debugDraw();
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0.5;
			fixtureDef.density=1
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(240/worldScale,240/worldScale);
			bodyDef.type=b2Body.b2_dynamicBody;
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,-234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(-234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			var circleShape:b2CircleShape=new b2CircleShape(0.5);
			fixtureDef.shape=circleShape;
			fixtureDef.isSensor=true;
			bodyDef.type=b2Body.b2_staticBody;
			bodyDef.position.Set(240/worldScale,240/worldScale);
			var jointPin:b2Body=world.CreateBody(bodyDef);
			jointPin.CreateFixture(fixtureDef);
			var containerJoint:b2RevoluteJointDef=new b2RevoluteJointDef();
			var anchorA:b2Vec2=new b2Vec2(0,0)
			var anchorB:b2Vec2=new b2Vec2(0,0)
			containerJoint.localAnchorA.Set(anchorA.x,anchorA.y);
			containerJoint.localAnchorB.Set(anchorB.x,anchorB.y);
			containerJoint.bodyA=container;
			containerJoint.bodyB=jointPin;
			containerJoint.enableMotor=true;
			containerJoint.maxMotorTorque=50000;
			containerJoint.motorSpeed=0.1;
			world.CreateJoint(containerJoint);
			for (var i:Number=0; i<12; i++) {
				addBox(Math.random()*300+50,Math.random()*300+50,38,38,true);
			}
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addBox(pX:Number,pY:Number,w:Number,h:Number,d:Boolean):void {
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			polygonShape.SetAsBox(w/worldScale/2,h/worldScale/2);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=1;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=polygonShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			if (d) {
				bodyDef.type=b2Body.b2_dynamicBody;
			}
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		private function debugDraw():void {
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function update(e:Event):void {
			world.Step(1/30, 10, 10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

Line 21: Makes the room a dynamic body

Lines 36-40: Create the static sphere, also set as a sensor to avoid collisions with the stuff inside the room

Lines 41-53: Pin the room to the sphere with a revolute joint and set a motor to make it rotate.

All transform-related code in update function should also be removed.

This is the result:

Now it works well but I wanted to remove the unnecessary sphere, so I decided to move onto step 3

3 - Pinning the room on the "ground" with a revolute joint

Box2D world also have a "ground" object (in this case I would call it "wall") which can be used to pin the dynamic body and apply the same revolute joint:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.Joints.*;
	public class Main extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,10),true);
		private var worldScale:Number=30;
		public function Main() {
			debugDraw();
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0.5;
			fixtureDef.density=1
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.position.Set(240/worldScale,240/worldScale);
			bodyDef.type=b2Body.b2_dynamicBody;
			var container:b2Body;
			container=world.CreateBody(bodyDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,-234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(480/worldScale/2,12/worldScale/2,new b2Vec2(0/worldScale,234/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(-234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			polygonShape.SetAsOrientedBox(12/worldScale/2,456/worldScale/2,new b2Vec2(234/worldScale,0/worldScale),0);
			fixtureDef.shape=polygonShape;
			container.CreateFixture(fixtureDef);
			var containerJoint:b2RevoluteJointDef=new b2RevoluteJointDef();
			var anchorA:b2Vec2=new b2Vec2(0,0)
			var anchorB:b2Vec2=new b2Vec2(240/worldScale,240/worldScale)
			containerJoint.localAnchorA.Set(anchorA.x,anchorA.y);
			containerJoint.localAnchorB.Set(anchorB.x,anchorB.y);
			containerJoint.bodyA=container;
			containerJoint.bodyB=world.GetGroundBody();
			containerJoint.enableMotor=true;
			containerJoint.maxMotorTorque=50000;
			containerJoint.motorSpeed=0.1;
			world.CreateJoint(containerJoint);
			for (var i:Number=0; i<12; i++) {
				addBox(Math.random()*300+50,Math.random()*300+50,38,38,true);
			}
			addEventListener(Event.ENTER_FRAME,update);
		}
		private function addBox(pX:Number,pY:Number,w:Number,h:Number,d:Boolean):void {
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			polygonShape.SetAsBox(w/worldScale/2,h/worldScale/2);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=1;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=polygonShape;
			var bodyDef:b2BodyDef = new b2BodyDef();
			if (d) {
				bodyDef.type=b2Body.b2_dynamicBody;
			}
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			var box:b2Body=world.CreateBody(bodyDef);
			box.CreateFixture(fixtureDef);
		}
		private function debugDraw():void {
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function update(e:Event):void {
			world.Step(1/30, 10, 10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

On line 42 you can see how to get the ground body.

And this is the final result:

I hope it can inspire you some new game design ideas.

Download the source code of the last example.

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