Do you like my tutorials?

Then consider supporting me on Ko-fi

Talking about Splitter game, Actionscript 3, Box2D, Flash and Users contributions.

Splitting Box2D objects seem to be the ultimate challenge around here… after The engine behind Splitter Flash game – first AS3 prototype, now we have two updates… the first by Guillaume Pommey, author of the previous prototype and the second one by Bryce Summer.

While Guillaume wants to refine a bit the final code before publishing it, here it is Bryce work:

Here is my messy attempt at recreating the splitter engine that you posted about on your blog. The code is VERY messy and it doesn’t really work but I decided to send it to you incase it would help at all. The controls are a little funky, you have to move the mouse over to the lower right corner so that the red line is across one of the shapes and click. Sometimes it will (sort of)split it, sometimes it will do nothing. Gravity is disabled at first, hold g to turn it on and release it to turn it off(I added the gravity toggle to try and figure out what was going wrong).

The actionscript resides in two files, one in the timeline and one in the Cutter class

This is the one in the timeline:

import Box2D.Dynamics.*;
import Box2D.Collision.*;
import Box2D.Collision.Shapes.*;
import Box2D.Dynamics.Joints.*;
import Box2D.Dynamics.Contacts.*;
import Box2D.Common.Math.*;
import Box2d.Common.*;

import flash.events.*;

addEventListener(Event.ENTER_FRAME, update, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mUp);
//stage.addEventListener(KeyboardEvent.KEY_DOWN, kDown);
//stage.addEventListener(KeyboardEvent.KEY_UP, kUp);

var MouseIsDown:Boolean = false;

var m_iterations:int = 10;
var m_timeStep:Number = 1/30;
var m_physScale:Number = 50;

var worldAABB:b2AABB = new b2AABB();
worldAABB.lowerBound.Set(-1000.0, -1000.0);
worldAABB.upperBound.Set(1000.0, 1000.0);

// Define the gravity vector
var gravity:b2Vec2 = new b2Vec2(0.0, 0.0);

// Allow bodies to sleep
var doSleep:Boolean = true;

// Construct a world object
var m_world = new b2World(worldAABB, gravity, doSleep);

var dbgDraw:b2DebugDraw = new b2DebugDraw();
//var dbgSprite:Sprite = new Sprite();
//m_sprite.addChild(dbgSprite);
dbgDraw.m_sprite = this;
dbgDraw.m_drawScale = 50.0;
dbgDraw.m_fillAlpha = 0.3;
dbgDraw.m_lineThickness = 1.0;
dbgDraw.m_drawFlags = b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit;
m_world.SetDebugDraw(dbgDraw);


var wallSd:b2PolygonDef = new b2PolygonDef();
var wallBd:b2BodyDef = new b2BodyDef();
var wallB:b2Body;

// Left
wallBd.position.Set(-95 / m_physScale, 360/m_physScale/2);
wallSd.SetAsBox(100/m_physScale, 400/m_physScale/2);
wallB = m_world.CreateBody(wallBd);
wallB.CreateShape(wallSd);
wallB.SetMassFromShapes();
// Right
wallBd.position.Set((640+95) / m_physScale, 360/m_physScale/2);
wallB = m_world.CreateBody(wallBd);
wallB.CreateShape(wallSd);
wallB.SetMassFromShapes();
// Top
wallBd.position.Set(640/m_physScale/2, -95/m_physScale);
wallSd.SetAsBox(680/m_physScale/2, 100/m_physScale);
wallB = m_world.CreateBody(wallBd);
wallB.CreateShape(wallSd);
wallB.SetMassFromShapes();
// Bottom
wallBd.position.Set(640/m_physScale/2, (360+95)/m_physScale);
wallB = m_world.CreateBody(wallBd);
wallB.CreateShape(wallSd);
wallB.SetMassFromShapes();

var body:b2Body;

// Spawn in a bunch of crap
for (var i = 0; i < 5; i++){
	var bodyDef:b2BodyDef = new b2BodyDef();
	//bodyDef.isBullet = true;
	var boxDef:b2PolygonDef = new b2PolygonDef();
	boxDef.density = 1.0;
	// Override the default friction.
	boxDef.friction = 0.3;
	boxDef.restitution = 0.1;
	boxDef.SetAsBox((Math.random() * 5 + 10) / m_physScale, (Math.random() * 5 + 10) / m_physScale);
	bodyDef.position.Set((Math.random() * 400 + 120) / m_physScale, (Math.random() * 150 + 50) / m_physScale);
	bodyDef.angle = Math.random() * Math.PI;
	body = m_world.CreateBody(bodyDef);
	body.CreateShape(boxDef);
	body.SetMassFromShapes();
	
}
/*
for (i = 0; i < 5; i++){
	var bodyDefC:b2BodyDef = new b2BodyDef();
	//bodyDefC.isBullet = true;
	var circDef:b2CircleDef = new b2CircleDef();
	circDef.density = 1.0;
	circDef.radius = (Math.random() * 5 + 10) / m_physScale;
	// Override the default friction.
	circDef.friction = 0.3;
	circDef.restitution = 0.1;
	bodyDefC.position.Set((Math.random() * 400 + 120) / m_physScale, (Math.random() * 150 + 50) / m_physScale);
	bodyDefC.angle = Math.random() * Math.PI;
	body = m_world.CreateBody(bodyDefC);
	body.CreateShape(circDef);
	body.SetMassFromShapes();
	
}
*/
for (i = 0; i < 15; i++){
	var bodyDefP:b2BodyDef = new b2BodyDef();
	//bodyDefP.isBullet = true;
	var polyDef:b2PolygonDef = new b2PolygonDef();
	if (Math.random() > 0.66){
		polyDef.vertexCount = 4;
		polyDef.vertices[0].Set((-10 -Math.random()*10) / m_physScale, ( 10 +Math.random()*10) / m_physScale);
		polyDef.vertices[1].Set(( -5 -Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
		polyDef.vertices[2].Set((  5 +Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
		polyDef.vertices[3].Set(( 10 +Math.random()*10) / m_physScale, ( 10 +Math.random()*10) / m_physScale);
	}
	else if (Math.random() > 0.5){
		polyDef.vertexCount = 5;
		polyDef.vertices[0].Set(0, (10 +Math.random()*10) / m_physScale);
		polyDef.vertices[2].Set((-5 -Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
		polyDef.vertices[3].Set(( 5 +Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
		polyDef.vertices[1].Set((polyDef.vertices[0].x + polyDef.vertices[2].x), (polyDef.vertices[0].y + polyDef.vertices[2].y));
		polyDef.vertices[1].Multiply(Math.random()/2+0.8);
		polyDef.vertices[4].Set((polyDef.vertices[3].x + polyDef.vertices[0].x), (polyDef.vertices[3].y + polyDef.vertices[0].y));
		polyDef.vertices[4].Multiply(Math.random()/2+0.8);
	}
	else{
		polyDef.vertexCount = 3;
		polyDef.vertices[0].Set(0, (10 +Math.random()*10) / m_physScale);
		polyDef.vertices[1].Set((-5 -Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
		polyDef.vertices[2].Set(( 5 +Math.random()*10) / m_physScale, (-10 -Math.random()*10) / m_physScale);
	}
	polyDef.density = 1.0;
	polyDef.friction = 0.3;
	polyDef.restitution = 0.1;
	bodyDefP.position.Set((Math.random() * 400 + 120) / m_physScale, (Math.random() * 150 + 50) / m_physScale);
	bodyDefP.angle = Math.random() * Math.PI;
	body = m_world.CreateBody(bodyDefP);
	body.CreateShape(polyDef);
	body.SetMassFromShapes();
}

function update(e:Event):void
{
	this.graphics.clear()
	m_world.Step(m_timeStep, m_iterations);
	
	var segment:b2Segment = new b2Segment();
	segment.p1.SetV(new b2Vec2(50 / m_physScale, 50 / m_physScale))
	segment.p2.SetV(new b2Vec2(mouseX / m_physScale, mouseY / m_physScale))
	//segment.ExtendForward(worldAABB);
	
	var lambda = [1];
	var normal:b2Vec2 = new b2Vec2();
	var maxShapes:Number = 64;
	var shapes:Array = new Array();
	var count:Number = m_world.Raycast(segment,shapes,maxShapes,false,null);
	
	if (MouseIsDown)
	{
		for (var i:int = 0; i < count; i++)
		{
			if (shapes[i].GetType() != b2Shape.e_polygonShape)
			{
				continue;
			}
			
			var b:b2Body = shapes[i].GetBody();
			
			if (b.GetMass() <= 0)
			{
				continue;
			}
			
			var polyShape:b2PolygonShape = shapes[i];
			var pd:Array = new Array(2);
			pd[0] = new b2PolygonDef();
			pd[0].density = 1;
			pd[1] = new b2PolygonDef();
			pd[1].density = 1;
			
			if (Cutter.SplitShape(polyShape, segment, 0.1, pd) == 0)
			{
				b.DestroyShape(shapes[i]);
				b.CreateShape(pd[0]);
				b.SetMassFromShapes();
				b.WakeUp();
				
				var bd:b2BodyDef = new b2BodyDef();
				bd.position = b.GetPosition();
				bd.angle = b.GetAngle();
				
				var newBody:b2Body = m_world.CreateBody(bd);
				newBody.CreateShape(pd[1]);
				newBody.SetMassFromShapes();
				newBody.SetAngularVelocity(b.GetAngularVelocity());
				newBody.SetLinearVelocity(b.GetLinearVelocity());
			}
		}
	}
	
	lambda=[1];
	lambda=lambda[0];
	
	this.graphics.lineStyle(1,0xff0000,1);
	this.graphics.moveTo(segment.p1.x * m_physScale, segment.p1.y * m_physScale);
	this.graphics.lineTo( 	(segment.p2.x * lambda + (1-lambda) * segment.p1.x) * m_physScale,
								(segment.p2.y * lambda + (1-lambda) * segment.p1.y) * m_physScale);
}

function mDown(e:MouseEvent):void
{
	MouseIsDown = true;
}

function mUp(e:MouseEvent):void
{
	MouseIsDown = false;
}
/*
var keyToCheck:String = "g";

function kDown(e:KeyboardEvent):void
{
	if (e.charCode == keyToCheck.charCodeAt(0))
	{
		m_world.SetGravity(new b2Vec2(0,10));
	}
}

function kUpp(e:KeyboardEvent):void
{
	if (e.charCode == keyToChek.charCodeAt(0))
	{
		m_world.SetGravity(new b2Vec2(0,0));
	}
}
*/

And this is Cutter.as

package
{
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Dynamics.Joints.*;
	import Box2D.Dynamics.Contacts.*;
	import Box2D.Common.Math.*;
	import Box2D.Common.*;
	
	public class Cutter
	{
		public static function CheckPolyShape(poly:b2PolygonDef):int
		{
			if (!(3 <= poly.vertexCount && poly.vertexCount <= b2Settings.b2_maxPolygonVertices))
			{
				return -1;
			}
			
			var m_normals:Array = new Array(poly.vertexCount);
			var i1:int;
			var i2:int;
			
			for (var i:int = 0; i < poly.vertexCount; i++)
			{
				i1 = i;
				i2 = i + 1 < poly.vertexCount ? i + 1 : 0;
				var edge:b2Vec2 = poly.vertices[i2].Copy();
				edge.Subtract(poly.vertices[i1]);
				
				if (!(edge.LengthSquared() > b2Settings.b2_linearSlop * b2Settings.b2_linearSlop))
				{
					return -1;
				}
				
				m_normals[i] = b2Math.b2CrossVF(edge, 1);
				m_normals[i].Normalize();
			}
			
			for (i = 0; i < poly.vertexCount; i++)
			{
				for (var j = 0; j < poly.vertexCount; j++)
				{
					if (j == i || j == (i + 1) % poly.vertexCount)
					{
						continue;
					}
					
					var aDot:b2Vec2 = poly.vertices[j].Copy();
					aDot.Subtract(poly.vertices[i]);
					var s:Number = b2Math.b2Dot(m_normals[i], aDot);
					if (!(s < -b2Settings.b2_linearSlop))
					{
						return -1;
					}
				}
			}
			
			for (i = 1; i < poly.vertexCount; i++)
			{
				var cross:Number = b2Math.b2CrossVV(m_normals[i-1], m_normals[i]);
				
				cross = b2Math.b2Clamp(cross, -1, 1);
				var angle:Number = Math.asin(cross);
				if (!(angle > b2Settings.b2_angularSlop))
				{
					return -1;
				}
			}
			
			var m_centroid:b2Vec2 = new b2Vec2();
			var area:Number = 0;
			var pRef:b2Vec2 = new b2Vec2();
			var inv3:Number = 1 / 3;
			
			for (i = 0; i < poly.vertexCount; i++)
			{
				var p1:b2Vec2 = pRef;
				var p2:b2Vec2 = poly.vertices[i];
				var p3:b2Vec2 = i + 1 < poly.vertexCount ? poly.vertices[i+1] : poly.vertices[0];
				
				var e1:b2Vec2 = p2.Copy();
				e1.Subtract(p1);
				var e2:b2Vec2 = p3.Copy();
				e2.Subtract(p1);
				
				var D:Number = b2Math.b2CrossVV(e1,e2);
				var triangleArea:Number = 0.5 * D;
				area += triangleArea;
				
				var p123:b2Vec2 = p1.Copy();
				p123.Add(p2);
				p123.Add(p3);
				var arInv3:Number = triangleArea * inv3;
				p123.Multiply(arInv3);
				m_centroid.Add(p123);
			}
			
			if (!(area > b2Settings.b2_linearSlop))
			{
				return -1;
			}
			m_centroid.Multiply(1 / area);
			
			for (i = 0; i < poly.vertexCount; i++)
			{
				i1 = i - 1 >= 0 ? i - 1 : poly.vertexCount - 1;
				i2 = i;
				
				var n1:b2Vec2 = m_normals[i1];
				var n2:b2Vec2 = m_normals[i2];
				var v:b2Vec2 = poly.vertices[i].Copy();
				v.Subtract(m_centroid);
				
				var d:b2Vec2 = new b2Vec2();
				d.x = b2Math.b2Dot(n1, v) - b2Settings.b2_toiSlop;
				d.y = b2Math.b2Dot(n2, v) - b2Settings.b2_toiSlop;
				
				if (!(d.x >= 0))
				{
					return -1;
				}
				
				if (!(d.y >= 0))
				{
					return -1;
				}
			}
			
			return 0;
		}
		
		public static function SplitShape(shape:b2PolygonShape, segment:b2Segment, splitSize:Number, newPolygon:Array):int
		{			
			var lambda:Array = [1];
			var normal:b2Vec2 = new b2Vec2();
			
			var b:b2Body = shape.GetBody();
			var xf:b2XForm = b.GetXForm();
			
			if (shape.TestSegment(xf, lambda, normal, segment, 1) != b2Shape.e_hitCollide)
			{
				return -1;
			}
			
			var entryPoint:b2Vec2 = segment.p1.Copy();
			entryPoint.Multiply(1 - lambda[0]);
			var tmp:b2Vec2 = segment.p2.Copy();
			tmp.Multiply(lambda[0]);
			entryPoint.Add(tmp);			
			
			var reverseSegment:b2Segment = new b2Segment();
			reverseSegment.p1 = segment.p2;
			reverseSegment.p2 = segment.p1;
			
			if (shape.TestSegment(xf, lambda, normal, reverseSegment, 1) != b2Shape.e_hitCollide)
			{
				return -1;
			}
			
			var exitPoint:b2Vec2 = reverseSegment.p1.Copy();
			exitPoint.Multiply(1 - lambda[0]);
			tmp = reverseSegment.p2.Copy();
			tmp.Multiply(lambda[0]);
			exitPoint.Add(tmp);			
			
			var localEntryPoint:b2Vec2 = b.GetLocalPoint(entryPoint);
			var localExitPoint:b2Vec2 = b.GetLocalPoint(exitPoint);
			
			var vertices:Array = shape.GetVertices();
			var cutAdded:Array = [-1,-1];
			var last:int = -1;
			
			for (var i:int = 0; i < shape.GetVertexCount(); i++)
			{
				var n:int;
				
				var subExitP:b2Vec2 = localExitPoint.Copy();
				subExitP.Subtract(localEntryPoint);
				var subVertex:b2Vec2 = vertices[i].Copy();
				subVertex.Subtract(localEntryPoint);
				if (b2Math.b2Dot(b2Math.b2CrossVF(subExitP, 1), subVertex) > 0)
				{
					n = 0;
				}
				
				else
				{
					n = 1;
				}
				
				if (last != n)
				{
					if (last == 0)
					{
						cutAdded[0] = newPolygon[last].vertexCount;
						newPolygon[last].vertices[newPolygon[last].vertexCount] = localExitPoint;
						newPolygon[last].vertexCount++;
						newPolygon[last].vertices[newPolygon[last].vertexCount] = localEntryPoint;
						newPolygon[last].vertexCount++;
					}
					
					if (last == 1)
					{
						cutAdded[last] = newPolygon[last].vertexCount;
						newPolygon[last].vertices[newPolygon[last].vertexCount] = localEntryPoint;
						newPolygon[last].vertexCount++;
						newPolygon[last].vertices[newPolygon[last].vertexCount] = localExitPoint;
						newPolygon[last].vertexCount++;
					}
				}
				newPolygon[n].vertices[newPolygon[n].vertexCount] = vertices[i];
				newPolygon[n].vertexCount++;
				last = n;
			}
			
			if (cutAdded[0] == -1)
			{
				cutAdded[0] = newPolygon[0].vertexCount;
				newPolygon[0].vertices[newPolygon[0].vertexCount] = localEntryPoint;
				newPolygon[0].vertexCount++;
				newPolygon[0].vertices[newPolygon[0].vertexCount] = localExitPoint;
				newPolygon[0].vertexCount++;
			}
			
			if (cutAdded[1] == -1)
			{
				cutAdded[1] = newPolygon[1].vertexCount;
				newPolygon[1].vertices[newPolygon[1].vertexCount] = localEntryPoint;
				newPolygon[1].vertexCount++;
				newPolygon[1].vertices[newPolygon[1].vertexCount] = localExitPoint;
				newPolygon[1].vertexCount++;
			}
			
			for (n = 0; n < 2; n++)
			{
				var offset:b2Vec2 = new b2Vec2();
				if (cutAdded[n] > 0)
				{
					offset = newPolygon[n].vertices[cutAdded[n]-1].Copy();
					offset.Subtract(newPolygon[n].vertices[cutAdded[n]]);
				}
				
				else
				{
					offset = newPolygon[n].vertices[newPolygon[n].vertexCount-1].Copy();
					offset.Subtract(newPolygon[n].vertices[0]);
				}
				
				offset.Normalize();
				offset.Multiply(splitSize);
				newPolygon[n].vertices[cutAdded[n]].Add(offset);
				
				if (cutAdded[n] < newPolygon[n].vertexCount-2)
				{
					offset = newPolygon[n].vertices[cutAdded[n]+2].Copy();
					offset.Subtract(newPolygon[n].vertices[cutAdded[n]+1]);
				}
				
				else
				{
					offset = newPolygon[n].vertices[0].Copy();
					offset.Subtract(newPolygon[n].vertices[newPolygon[n].vertexCount-1]);
				}
				
				offset.Normalize();
				offset.Multiply(splitSize);
				
				newPolygon[n].vertices[cutAdded[n]+1].Add(offset);
			}
			
			for (n = 0; n < 2; n++)
			{
				if (CheckPolyShape(newPolygon[n]))
				{
					return -1;
				}
			}
			
			return 0;
		}
	}
}

This is the final result:

And this is the source to download

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.