2dx_icon_512_rounded

Cocos2dx-js + Chipmunk – Part 6: Creating static physics object

Welcome in the next part of Cocos2dx-js + Chipmunk tutorial. As far we learnt how to create circle, square, rectangle and complex physics object. Each kind of them is smoothly simulated in the physics space. But what to do when we want to create a static object, for example some kind of platform? This we learn in today’s tutorial.

As always, I assume that you have project created with previous parts of this tutorial.

1. Rectangle.png
Our static platform will be a rectangle. From previous tutorial you should have this sprite in your assets, but here is again. If you don’t have this image in your resources, copy it and paste to your $PROJECT-DIR/Resources/images/resources-auto
rectangle

2. Function to static box (rectangle/square) object.
To our PhysicsScene.js let’s add following function:

function addStaticObject() {
	//#1
	//here should be PhysicsSprite

	//#2
	staticBody = new cp.Body(Infinity, Infinity);

	staticSprite = cc.Sprite.create("rectangle.png");
	controller.addChild(staticSprite);
	staticSprite.setPosition(cc.p(winSize.width * 0.5, winSize.height * 0.5));

	staticBody.setPos(staticSprite.getPosition());
	shape = new cp.BoxShape(staticBody, staticSprite.getContentSize().width, staticSprite.getContentSize().height);
	shape.setElasticity(1);
	shape.setFriction(1);
	space.addShape(shape);
}

There are two main differences between previous used functions:
#1 – First of all is that we don’t need PhysicsSprite object anymore – the core is not simulated.
#2 – The second difference is that Body has both Infinity mass and Infinity moment for box.
In Chipmunk, Infinity is a static constant variable that means some “infinity” or “max” value.

3. Execute function
Add this lines:

addStaticObject();

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");

	addStaticObject();
}

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

physicsPart5

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