Basic Box2D rope-chain: 2.1a version

I was playing with the web version of Cut the Rope when it came to my mind the idea of showing you how to create a cut the rope game.

I knew about two years ago I wrote a tutorial about a basic Box2D rope and I wanted to start from here, but unfortunately it does not work with 2.1a version.

So at the moment I made a Box2D rope-chain version working with 2.1a, whose theory is based on the same concept of the original post with intensive use of revolute joints.

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 worldScale:Number=30;
		private var world:b2World;
		// this is the ball which I'll join at the end of the chain/rope
		private var steelBall:b2Body;
		public function Main() {
			// number of links forming the rope
			var links:Number=Math.floor(Math.random()*10)+2;
			// according to the number of links, I am setting the length of a single chain piace
			var chainLength:Number=180/links;
			// creation of a new world
			world=new b2World(new b2Vec2(0,10),true);
			debugDraw();
			// ceiling polygon shape
			var polygonShape:b2PolygonShape = new b2PolygonShape();
			polygonShape.SetAsBox(320/worldScale,10/worldScale);
			// ceiling fixture;
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=1;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=polygonShape;
			// ceiling body
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.position.Set(320/worldScale,0);
			// ceiling creation;
			var wall:b2Body=world.CreateBody(bodyDef);
			wall.CreateFixture(fixtureDef);
			// link polygon shape
			polygonShape.SetAsBox(5/worldScale,chainLength/worldScale);
			// link fixture;
			fixtureDef.density=1;
			fixtureDef.shape=polygonShape;
			// link body
			bodyDef.type=b2Body.b2_dynamicBody;
			// link creation
			for (var i:Number=0; i<=links; i++) {
				bodyDef.position.Set(320/worldScale,(chainLength+2*chainLength*i)/worldScale);
				if (i==0) {
					var link:b2Body=world.CreateBody(bodyDef);
					link.CreateFixture(fixtureDef);
					revoluteJoint(wall,link,new b2Vec2(0,0),new b2Vec2(0,-chainLength/worldScale));
				}
				else {
					var newLink:b2Body=world.CreateBody(bodyDef);
					newLink.CreateFixture(fixtureDef);
					revoluteJoint(link,newLink,new b2Vec2(0,chainLength/worldScale),new b2Vec2(0,-chainLength/worldScale));
					link=newLink;
				}
			}
			// attaching the ball at the end of the rope
			var circleShape:b2CircleShape=new b2CircleShape(1);
			fixtureDef.shape=circleShape;
			steelBall=world.CreateBody(bodyDef);
			steelBall.CreateFixture(fixtureDef);
			revoluteJoint(link,steelBall,new b2Vec2(0,chainLength/worldScale),new b2Vec2(0,0));
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.CLICK,sphereImpulse);
		}
		// this is the core of the script: despite the official docs which suggest to use Initialize,
		// use this method instead
		private function revoluteJoint(bodyA:b2Body,bodyB:b2Body,anchorA:b2Vec2,anchorB:b2Vec2):void {
			var revoluteJointDef:b2RevoluteJointDef=new b2RevoluteJointDef();
			revoluteJointDef.localAnchorA.Set(anchorA.x,anchorA.y);
			revoluteJointDef.localAnchorB.Set(anchorB.x,anchorB.y);
			revoluteJointDef.bodyA=bodyA;
			revoluteJointDef.bodyB=bodyB;
			world.CreateJoint(revoluteJointDef);
		}
		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 sphereImpulse(e:MouseEvent):void {
			// just apply an impulse to the sphere
			steelBall.ApplyImpulse(new b2Vec2(-50+Math.random()*100,-150),steelBall.GetWorldCenter());
		}
		private function update(e:Event):void {
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

The key lies in the revoluteJoint function which acts directly on b2RevoluteJointDef properties rather than unsing Initialize method which is not that efficient.

This is the result:

Click on the stage to add a random impulse to the sphere. The number and length of links is random, so refresh the page to see a different rope.

Download the source code and see you soon with a Cut the Rope tutorial.

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