Way of an Idea Box2D prototype – Step 3

Read all posts about "" game

Welcome to the 3rd part. In part 2 we allowed the player to draw the chalk track in a “paused” Box2D environment and then run the simulation.

Now it’s time to delete our chalk track.

A bit of theory: although the simulation is paused, the chalk bodies are already placed in the Box2D world. So we can easily select them with our old friend GetBodyAtMouse function.

Then we need to know whether the selected body is a chalk or not… we don’t want to delete other level assets or even the ball!!

So we must check if the userData of the selected body (that is the attached sprite) is a chalk. If true, we can remove the sprite from the stage and destroy the body.

This is the code:

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.*;
	public class draw extends Sprite {
		public var drawing:Boolean=false;
		public var canvas:Sprite = new Sprite();
		public var points_array:Array;
		public var pixel_dist:int=20;
		public var saved_x:int;
		public var saved_y:int;
		public var m_world:b2World;
		public var body:b2Body;
		public var bodyDef:b2BodyDef = new b2BodyDef();
		public var circleDef:b2CircleDef= new b2CircleDef();
		public var mousePVec:b2Vec2 = new b2Vec2();
		// radians to degrees conversion
		public var rad_to_deg:Number=57.2957795;
		// simulation timestep. We start at zero.
		public var timestep:Number=0;
		public function draw():void {
			// world creation
			var worldAABB:b2AABB = new b2AABB();
			worldAABB.lowerBound.Set(-100.0, -100.0);
			worldAABB.upperBound.Set(100.0, 100.0);
			m_world=new b2World(worldAABB,new b2Vec2(0,10),true);
			//
			// *** IMPORTANT: NOTICE THERE ISN'T ANY DEBUG DRAW ROUTINE ***
			// 
			// placing the ball
			bodyDef.position.Set(20/30,20/30);
			circleDef.radius=15/30;
			circleDef.density=1;
			circleDef.friction=0.5;
			circleDef.restitution=0.2;
			// ball's movieclip attachment
			bodyDef.userData = new sphere();
			bodyDef.userData.x=20;
			bodyDef.userData.y=20;
			bodyDef.userData.width=30;
			bodyDef.userData.height=30;
			addChild(bodyDef.userData);
			// end ball's movieclip attachment
			body=m_world.CreateBody(bodyDef);
			body.CreateShape(circleDef);
			body.SetMassFromShapes();
			//
			addChild(canvas);
			canvas.graphics.lineStyle(5);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mouse_pressed);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouse_moved);
			stage.addEventListener(MouseEvent.MOUSE_UP,mouse_released);
			addEventListener(Event.ENTER_FRAME, Update, false, 0, true);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, key_down);

		}
		public function mouse_pressed(e:MouseEvent):void {
			drawing=true;
			canvas.graphics.moveTo(mouseX,mouseY);
			points_array=new Array();
			saved_x=mouseX;
			saved_y=mouseY;
			points_array.push(saved_x);
			points_array.push(saved_y);
		}
		public function mouse_moved(e:MouseEvent):void {
			if (drawing) {
				var dist_x:int=mouseX-saved_x;
				var dist_y:int=mouseY-saved_y;
				if (dist_x*dist_x+dist_y*dist_y>pixel_dist*pixel_dist) {
					canvas.graphics.lineTo(mouseX,mouseY);
					saved_x=mouseX;
					saved_y=mouseY;
					points_array.push(saved_x);
					points_array.push(saved_y);
				}
			}
		}
		public function mouse_released(e:MouseEvent):void {
			drawing=false;
			var sx:int;
			var ex:int;
			var sy:int;
			var ey:int;
			var dist_x:int;
			var dist_y:int;
			var dist:Number;
			var angle:Number;
			var segments:int=points_array.length/2-1;
			for (var i:int=0; i

And this is the result:

Draw the track with your mouse, press SPACE to begin the simulation and delete the chalk pressing 0 (zero) and moving the mouse over the chalk.

No need to download anything since you can easily cut-paste this code on the Step 2 example

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