Flash physics draw game with a car using QuickB2

Read all posts about "" game

QuickB2 is a complete abstraction of Box2D, providing grouped hierarchies, extensible classes, and event-driven callbacks.

The high-level interface enables developers to create physics simulations that are impractical to write using Box2D’s API alone.

It takes care of things that you don’t want to, so that you can concentrate on your game.

Among its top features we can find:

* Soft-bodies.
* Top-down car physics.
* Friction in z-direction (top-down friction).
* Pixel-based units.
* Individual polygons may be concave and have any number of vertices.
* All kinds of joints, including built-in spring joints.
* WYSIWYG editing environment for Flash CS5.

Combining one of the official examples with the drawing concept introduced during the creation of Way of an Idea Box2D prototype I ended up with this script:

package {
	import As3Math.consts.*;
	import As3Math.geo2d.*;
	import QuickB2.events.*;
	import QuickB2.misc.*;
	import QuickB2.objects.*;
	import QuickB2.objects.joints.*;
	import QuickB2.objects.tangibles.*;
	import QuickB2.stock.*;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	public class Main extends Sprite {
		private var car:qb2Group;
		private var world:qb2World;
		private var left:Boolean=false;
		private var right:Boolean=false;
		private var drawing:Boolean=false;
		private var canvas:Sprite = new Sprite();
		private var pointsArray:Array;
		private var drawDistance:int=60;
		private var saveX:int;
		private var saveY:int;
		public function Main():void {
			world=qb2Stock.newDebugWorld(new amVector2d(0,10),this.graphics);
			world.start();
			var rectangle:qb2PolygonShape=qb2Stock.newRectShape(new amPoint2d(200,200),100,25,0);
			world.addObject(rectangle);
			world.addObject(new qb2StageWalls(stage));
			var carOrigin:amPoint2d=new amPoint2d(200,150);
			var wheelRadius:Number=20;
			var bodyLength:Number=60;
			var bodyHeight:Number=20;
			var alteredFriction:Number=2;
			car = new qb2Group();
			var wheel1:qb2CircleShape=qb2Stock.newCircleShape(carOrigin.clone().incX(- bodyLength/2),wheelRadius,1);
			var wheel2:qb2CircleShape = qb2Stock.newCircleShape(carOrigin.clone().incX( bodyLength / 2), wheelRadius, 1);
			var carBody:qb2PolygonShape = qb2Stock.newEllipseShape(carOrigin.clone().incY( -bodyLength / 2), new amVector2d(bodyLength/2 + 10, 0), bodyHeight, 18, 0, 2 * AM_PI, 2);
			wheel1.friction=wheel2.friction=alteredFriction;
			wheel1.angularDamping=wheel2.angularDamping=.1;
			var leftSpring:qb2PistonJoint=new qb2PistonJoint(carBody,wheel1,carBody.position.clone().incX(- bodyLength/2),wheel1.position);
			var rightSpring:qb2PistonJoint = new qb2PistonJoint(carBody, wheel2, carBody.position.clone().incX( bodyLength/2), wheel2.position);
			leftSpring.springK=50;
			rightSpring.springK=50;
			leftSpring.springDamping=2;
			rightSpring.springDamping=2;
			leftSpring.freeRotation=true;
			rightSpring.freeRotation=true;
			car.addObject(carBody);
			car.addObject(wheel1);
			car.addObject(wheel2);
			car.addObject(leftSpring);
			car.addObject(rightSpring);
			world.addObject(car);
			addChild(canvas);
			canvas.graphics.lineStyle(5);
			car.addEventListener(qb2UpdateEvent.POST_UPDATE, updateCar);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
			stage.addEventListener(KeyboardEvent.KEY_UP,keyReleased);
		}
		private function keyPressed(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=true;
					break;
				case 39 :
					right=true;
					break;
			}
		}
		private function keyReleased(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=false;
					break;
				case 39 :
					right=false;
					break;
			}
		}
		private function mousePressed(e:MouseEvent):void {
			drawing=true;
			canvas.graphics.moveTo(mouseX,mouseY);
			pointsArray=new Array();
			saveX=mouseX;
			saveY=mouseY;
			pointsArray.push(saveX);
			pointsArray.push(saveY);
		}
		private function mouseMoved(e:MouseEvent):void {
			if (drawing) {
				var dist_x:int=mouseX-saveX;
				var dist_y:int=mouseY-saveY;
				if (dist_x*dist_x+dist_y*dist_y>drawDistance*drawDistance) {
					canvas.graphics.lineTo(mouseX,mouseY);
					saveX=mouseX;
					saveY=mouseY;
					pointsArray.push(saveX);
					pointsArray.push(saveY);
				}
			}
		}
		private function mouseReleased(e:MouseEvent):void {
			drawing=false;
			var segments:int=pointsArray.length/2-1;
			for (var i:int=0; i

which once executed produces this result:

Control the car with left and right arrow keys, and draw ramps with the mouse.

Now I am doing the same thing with the normal Box2D library to show you the differences.

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