Quick 3D physics with Away3D 4.1 and Bullet Physics Engine

I really like when 3D and physics are easy to use, because game developers can delight us with new and original creations.

Two years ago I also made a 3D physics game called CubesOut, which was also licensed under the Pod Training name for the Mass Effect 3 official site.

Back to our days, here I am to show you probably the first tutorial you can find online about Away3D 4.1 and its integrated Bullet Physics Engine.

Everyting is commented in the code, which will allow you to create random cubes with the mouse. I know it’s quite simple but we are starting from the very beginning.

Here is the code:

package {
	// flash classes
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Vector3D;
	// away3d classes
	import away3d.containers.View3D;
	import away3d.entities.Mesh;
	import away3d.materials.ColorMaterial;
	import away3d.primitives.CubeGeometry;
	import away3d.lights.PointLight;
	import away3d.lights.LightBase;
	import away3d.materials.lightpickers.StaticLightPicker
	// awayphysics classes
	import awayphysics.collision.shapes.AWPBoxShape;
	import awayphysics.dynamics.AWPDynamicsWorld;
	import awayphysics.dynamics.AWPRigidBody;
	public class Main extends Sprite {
		// View3D is the Away3D world
		private var mainView:View3D;
		// AWPDynamicsWorld is the physics world
		private var world:AWPDynamicsWorld;
		// a point light, to add some (guess what?) light to the scene
		private var light:PointLight;
		public function Main() {
			// initializing the physics world
			world=AWPDynamicsWorld.getInstance();
			world.initWithDbvtBroadphase();
			// initializing the 3D world
			mainView = new View3D();
			addChild(mainView);
			// creating a new point light, all properties are easy to understand
			light = new PointLight();
            light.y = 1000;
            light.z = -700;
			light.color = 0xffff00;
			// adding the light to the scene
            mainView.scene.addChild(light);
			// setting camera position
			mainView.camera.z=-600;
			mainView.camera.y=500;
			// setting camera target
			mainView.camera.lookAt(new Vector3D(0,0,0));
			// the floor is a big rectangular cuboid, here is how we define it in Away3D
			var floorMesh:Mesh=new Mesh(new CubeGeometry(1000,5,1000));
			// defining a material
			var material:ColorMaterial=new ColorMaterial(0xa90000);
			// the material will be affected by light
			material.lightPicker = new StaticLightPicker([light]);
			// finally assigning the material to the floor cuboid
			floorMesh.material=material;
			// adding the cuboid to 3D world
			mainView.scene.addChild(floorMesh);
			// time to create its physics alter ego: notice AWPBoxShape and CubeGeometry have the same arguments
			var floorShape:AWPBoxShape=new AWPBoxShape(1000,5,1000);
			// link the physics cuboid with the 3D cuboid, the final "0" argument means it's static
			var floorRigidBody:AWPRigidBody=new AWPRigidBody(floorShape,floorMesh,0);
			// adding the physics body to the world
			world.addRigidBody(floorRigidBody);
			floorRigidBody.friction=1;
			floorRigidBody.position=new Vector3D(0,0,0);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.CLICK,addCube);
		}
		// this function creates a cube in the same way seen before
		private function addCube(e:MouseEvent):void {
			var cubeMesh:Mesh=new Mesh(new CubeGeometry(50,50,50));
			cubeMesh.material=new ColorMaterial();
			cubeMesh.material.lightPicker = new StaticLightPicker([light]);
			mainView.scene.addChild(cubeMesh);
			var cubeShape:AWPBoxShape=new AWPBoxShape(50,50,50);
			var cubeRigidBody:AWPRigidBody=new AWPRigidBody(cubeShape,cubeMesh,1); // notice the final "1" as it's dynamic
			world.addRigidBody(cubeRigidBody);
			cubeRigidBody.friction=1;
			cubeRigidBody.position=new Vector3D(Math.random()*600-300,400,Math.random()*600-300);
		}
		private function update(e:Event):void {
			// first, we iterate the physics engine...
			world.step(1/30, 1, 1/30);
			// then we render the 3D scene
			mainView.render();
		}
	}
}

And this is the result:

Click with the mouse to generate random cubes.

To get all required libraries, you have to download Away3D 4.1.0 Alpha and awayphysics.

Download the source code with all required libraries.

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

215 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
// Stairs
// 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