2dx_icon_512_rounded

Cocos2dx-js + Chipmunk – Part 4: Creating rectangle & square physics object

Hello, today we will learn how to add not only circle physics shapes but also the square and rectangle ones.
As always, I assume that you have project created with previous parts of this tutorial.

1. Rectangle.png & square.png
Here you have sprite representing rectangle and square that we will use to create our physics object. Copy it and paste to your $PROJECT-DIR/Resources/images/resources-auto
rectangle square

2. Function to create both rectangle and square (box) physics object.
To our PhysicsScene.js let’s add following function:

function addPhysicsBox(filename) {
	//#1
	box = cc.Sprite.create(filename);
	mass = 10;

	//#2
	var nodeSize = box.getContentSize(),
		phNode = cc.PhysicsSprite.create(filename),
		phBody = null,
		phShape = null,
		scaleX = 1,
		scaleY = 1;
	nodeSize.width *= scaleX;
	nodeSize.height *= scaleY;

	//#3
	phBody = space.addBody(new cp.Body(mass, cp.momentForBox(mass, nodeSize.width, nodeSize.height)));
	phBody.setPos(cc.p(winSize.width * Math.random(), winSize.height * Math.random()));

	//#4
	shape = space.addShape(new cp.BoxShape(phBody, nodeSize.width, nodeSize.height));
	shape.setFriction(0.5);
	shape.setElasticity(0.5);

	phNode.setBody(phBody);
	phNode.setRotation(0);
	phNode.setScale(1);

	controller.addChild(phNode);
}

The main differences between similar code from previous tutorial are:
#1 To create sprite we pass parameter filename
#2 Secondly we create PhysicsNode based on the created sprite but still with parameter filename. We set width, height, scale and image.
#3 Here we don’t use cp.momentForCircle but cp.momentForBox
#4 Then we create PhysicsShape which describes what kind of body it will be. But we use BoxShape, not CircleShape. nodeSize.width, nodeSize.height parameters set the size of shape
As you can see, filename parameter allow us to reuse one function both to create rectangle and square.

3. Execute function
Add this lines:

addPhysicsBox("square.png");
addPhysicsBox("rectangle.png");

to your init method.
For me it looks like this:

PhysicsScene.prototype.init = function() {
	cc.Director.getInstance().setDisplayStats(false);
	initPhysics();
	initDebugMode(controller);

	addWallsAndGround();
	addPhysicsCircle();
	addPhysicsBox("square.png");
	addPhysicsBox("rectangle.png");
}

4. Compile and run
Let’s see what happen:
physicsPart2

 

Sourcehttps://bitbucket.org/galante/chipmunktutorialresources/commits/branch/master