Real world catapult prototype using Box2D – Adding wheels

Read all posts about "" game

Did you enjoy the catapult prototype?

Here I am with the second part, adding wheels controlled by left and right arrows.

Have a look:

Now you can move the catapult with left and arrow keys, and shoot with a mouse click

If you feel the catapult is running on an icy surface, that’s because I did not set any friction. I’ll do it next time, when I’ll also come with a decent code, meanwhile check this:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.Joints.*;
	public class main extends Sprite {
		public var world:b2World=new b2World(new b2Vec2(0,10.0),true);
		public var world_scale:int=30;
		var arm_joint:b2RevoluteJointDef = new b2RevoluteJointDef();
		var front_wheel_joint:b2RevoluteJointDef = new b2RevoluteJointDef();
		var rear_wheel_joint:b2RevoluteJointDef = new b2RevoluteJointDef();
		var arm_revolute_joint_def:b2RevoluteJoint;
		var front_wheel_joint_def:b2RevoluteJoint;
		var rear_wheel_joint_def:b2RevoluteJoint;
		var catapult_body:b2BodyDef = new b2BodyDef();
		var catapult_itself:b2Body;
		public function main():void {
			debug_draw();
			draw_box(250,400,2000,30,false,"ground");
			catapult_body.position.Set(350/world_scale,200/world_scale);
			catapult_body.type=b2Body.b2_dynamicBody;
			var main_part:b2PolygonShape = new b2PolygonShape();
			main_part.SetAsOrientedBox(125/world_scale, 20/world_scale, new b2Vec2(0,0),0);
			var fixed_arm:b2PolygonShape = new b2PolygonShape();
			fixed_arm.SetAsOrientedBox(20/world_scale, 60/world_scale, new b2Vec2(-80/world_scale,-40/world_scale),0);
			catapult_itself=world.CreateBody(catapult_body);
			catapult_itself.CreateFixture2(main_part,200);
			catapult_itself.CreateFixture2(fixed_arm,200);
			var catapult_arm:b2BodyDef = new b2BodyDef();
			catapult_arm.allowSleep=false;
			catapult_arm.position.Set(210/world_scale,110/world_scale);
			catapult_arm.type=b2Body.b2_dynamicBody;
			var arm_part:b2PolygonShape = new b2PolygonShape();
			arm_part.SetAsOrientedBox(150/world_scale, 10/world_scale, new b2Vec2(0,0),0);
			var stopper:b2PolygonShape = new b2PolygonShape();
			stopper.SetAsOrientedBox(10/world_scale, 20/world_scale, new b2Vec2(-140/world_scale,-30/world_scale),0);
			var catapult_arm_itself:b2Body=world.CreateBody(catapult_arm);
			catapult_arm_itself.CreateFixture2(arm_part,1);
			catapult_arm_itself.CreateFixture2(stopper,1);
			//
			arm_joint.enableMotor=true;
			arm_joint.enableLimit=true;
			arm_joint.Initialize(catapult_itself, catapult_arm_itself,new b2Vec2(0,0));
			arm_joint.localAnchorA=new b2Vec2(-80/world_scale,-90/world_scale);
			arm_joint.localAnchorB=new b2Vec2(60/world_scale,0);
			arm_revolute_joint_def=world.CreateJoint(arm_joint) as b2RevoluteJoint;
			arm_revolute_joint_def.SetMotorSpeed(1000);
			arm_revolute_joint_def.SetLimits(-Math.PI,Math.PI/3);
			arm_revolute_joint_def.SetMaxMotorTorque(1);
			//
			var rear_wheel:b2BodyDef= new b2BodyDef();
			rear_wheel.position.Set(250/world_scale, 200/world_scale);
			rear_wheel.type=b2Body.b2_dynamicBody;
			var rear_wheel_shape:b2CircleShape=new b2CircleShape(40/world_scale);
			var the_rear_wheel_itself:b2Body=world.CreateBody(rear_wheel);
			the_rear_wheel_itself.CreateFixture2(rear_wheel_shape,20);
			var front_wheel:b2BodyDef= new b2BodyDef();
			front_wheel.position.Set(450/world_scale, 200/world_scale);
			front_wheel.type=b2Body.b2_dynamicBody;
			var front_wheel_shape:b2CircleShape=new b2CircleShape(40/world_scale);
			var the_front_wheel_itself:b2Body=world.CreateBody(front_wheel);
			the_front_wheel_itself.CreateFixture2(front_wheel_shape,20);
			//
			front_wheel_joint.enableMotor=true;
			front_wheel_joint.Initialize(catapult_itself, the_front_wheel_itself,new b2Vec2(0,0));
			front_wheel_joint.localAnchorA=new b2Vec2(80/world_scale,0);
			front_wheel_joint.localAnchorB=new b2Vec2(0,0);
			front_wheel_joint_def=world.CreateJoint(front_wheel_joint) as b2RevoluteJoint;
			front_wheel_joint_def.SetMaxMotorTorque(1000000);
			//
			rear_wheel_joint.enableMotor=true;
			rear_wheel_joint.Initialize(catapult_itself, the_rear_wheel_itself,new b2Vec2(0,0));
			rear_wheel_joint.localAnchorA=new b2Vec2(-80/world_scale,0);
			rear_wheel_joint.localAnchorB=new b2Vec2(0,0);
			rear_wheel_joint_def=world.CreateJoint(rear_wheel_joint) as b2RevoluteJoint;
			rear_wheel_joint_def.SetMaxMotorTorque(1000000);
			//
			var cannonball:b2BodyDef= new b2BodyDef();
			cannonball.position.Set(90/world_scale, 90/world_scale);
			cannonball.type=b2Body.b2_dynamicBody;
			var ball:b2CircleShape=new b2CircleShape(10/world_scale);
			var the_cannonball_itself:b2Body=world.CreateBody(cannonball);
			the_cannonball_itself.CreateFixture2(ball,20);
			addEventListener(Event.ENTER_FRAME, update);
			stage.addEventListener(MouseEvent.CLICK,fire);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, key_down);
		}
		public function key_down(event:KeyboardEvent):void {
			switch (event.keyCode) {
				case 39 :
					rear_wheel_joint_def.SetMotorSpeed(10);
					front_wheel_joint_def.SetMotorSpeed(10);
					break;
				case 37 :
					rear_wheel_joint_def.SetMotorSpeed(-10);
					front_wheel_joint_def.SetMotorSpeed(-10);
					break;
			}
		}

		public function fire(e:MouseEvent):void {
			arm_revolute_joint_def.SetMaxMotorTorque(10000);
		}
		public function draw_box(px,py,w,h,d,ud):void {
			var ground:b2BodyDef= new b2BodyDef();
			ground.position.Set(px/world_scale, py/world_scale);
			if (d) {
				ground.type=b2Body.b2_dynamicBody;
			}
			var my_box:b2PolygonShape = new b2PolygonShape();
			my_box.SetAsBox(w/2/world_scale, h/2/world_scale);
			var my_fixture:b2FixtureDef = new b2FixtureDef();
			my_fixture.shape=my_box;
			var the_ground_itself:b2Body=world.CreateBody(ground);
			the_ground_itself.SetUserData(ud);
			the_ground_itself.CreateFixture(my_fixture);
		}
		public function debug_draw():void {
			var debug_draw:b2DebugDraw = new b2DebugDraw();
			var debug_sprite:Sprite = new Sprite();
			addChild(debug_sprite);
			debug_draw.SetSprite(debug_sprite);
			debug_draw.SetDrawScale(world_scale);
			debug_draw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debug_draw.SetFillAlpha(0.5);
			world.SetDebugDraw(debug_draw);
		}
		public function update(e:Event):void {
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

No need to download anything, just paste the new code in the catapult prototype file.

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