An one-button way to control the player coming from the past – Box2D version (introducing friction joints)

Read all posts about "" game

This is a quick attempt to port the engine of the one-button way to control the player coming from the past using Box2D, introducing for the first time the friction joint, a type of joint which is poorly explained in the tutorial you can see around the web, and it’s a pity because it’s very useful when you have to handle with top down simulations.

Basically I created a world with no gravity, then I created a friction joint between the ball controlled by the player and the “ground”, in this case the world body.

The final result is a lot more realistic than any other result you can achieve using linear damping or other tricks.

This is the source code:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	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,0),true);
		private var worldScale:Number=30;
		private var theBall:b2Body;
		private var ball:Ball=new Ball();
		private var directionArrow:DirectionArrow=new DirectionArrow();
		private var powerText:TextField = new TextField();
		private var rotate:Boolean=true;
		private var power:Number=0;
		private var rotationSpeed:Number=5;
		public function Main() {
			debugDraw();
			createBall();
			addChild(ball);
			ball.x=320;
			ball.y=240;
			ball.addChild(directionArrow);
			powerText.textColor=0xffffff;
			powerText.y=-10;
			powerText.x=-5;
			powerText.visible=false;
			ball.addChild(powerText);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,prepareLaunch);
			stage.addEventListener(MouseEvent.MOUSE_UP,launch);
		}
		private function createBall():void {
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.restitution=0;
			fixtureDef.density=1;
			var circleShape:b2CircleShape=new b2CircleShape(10/worldScale);
			fixtureDef.shape=circleShape;
			var bodyDef:b2BodyDef=new b2BodyDef();
			bodyDef.userData=new Sprite();
			bodyDef.position.Set(320/worldScale,240/worldScale);
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.userData=ball;
			theBall=world.CreateBody(bodyDef);
			theBall.CreateFixture(fixtureDef);
			var frictionJointDef:b2FrictionJointDef = new b2FrictionJointDef();
			var anchorA:b2Vec2=new b2Vec2(0,0);
			var anchorB:b2Vec2=new b2Vec2(320/worldScale,240/worldScale);
			frictionJointDef.localAnchorA=anchorA;
			frictionJointDef.localAnchorB=anchorB;
			frictionJointDef.bodyA=theBall;
			frictionJointDef.bodyB=world.GetGroundBody();
			frictionJointDef.maxForce=0.5;
			frictionJointDef.maxTorque=5;
			world.CreateJoint(frictionJointDef as b2JointDef);
		}
		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 prepareLaunch(e:MouseEvent):void {
			powerText.visible=true;
			rotate=false;
		}
		private function launch(e:MouseEvent):void {
			if (! rotate) {
				powerText.visible=false;
				rotate=true;
				theBall.ApplyImpulse(new b2Vec2(power*Math.cos((directionArrow.rotation-90)*0.0174532925)/10,power*Math.sin((directionArrow.rotation-90)*0.0174532925)/10),theBall.GetWorldCenter());
				power=0;
				rotationSpeed*=-1;
			}
		}
		private function update(e:Event):void {
			world.Step(1/30, 10, 10);
			if (rotate) {
				directionArrow.rotation+=rotationSpeed;
			}
			else {
				power++;
				power=Math.min(power,50);
				powerText.text=power.toString();
			}
			for (var b:b2Body = world.GetBodyList(); b; b = b.GetNext()) {
				if (b.GetUserData()!=null) {
					b.GetUserData().x=b.GetPosition().x*worldScale;
					b.GetUserData().y=b.GetPosition().y*worldScale;
				}
			}
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

and this is the result:

You know how to “play”: press and keep the mouse pressed to move the ball with a given direction and speed. Also look at the friction joint in the debug draw.

Download the source code

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