2dx_icon_512_rounded

Cocos2dx-js + Chipmunk – Part 3: Creating circle physics object

Hello, today we will finally have fun with physics simulations – we create our first real physics object – circle.
As always, I assume that you have project created with previous parts of this tutorial.

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

2. Function to create circle physics object.
To our PhysicsScene.js let’s add following function:

function addPhysicsCircle() {
	//#1
	circle = cc.Sprite.create("circle.png");
	mass = 10;

	//#2
	var nodeSize = circle.getContentSize(),
		phNode = cc.PhysicsSprite.create("circle.png"),
		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 * 0.5, winSize.height * 0.5));

	//#4
	phShape = space.addShape(new cp.CircleShape(phBody, nodeSize.width * 0.5, cc.p(0, 0)));
	phShape.setFriction(0.5);
	phShape.setElasticity(1);

	//#5
	phNode.setBody(phBody);
	phNode.setRotation(0);
	phNode.setScale(1);

	controller.addChild(phNode);
}

#1 First of all we create simple sprite and init mass variable to 10.
#2 Secondly we create PhysicsNode based on the created sprite. We set width, height, scale and image.
#3 Next step is to create PhysicsSprite with mass and dimensions of previously created PhysicsSprite.
#4 Then we create PhysicsShape which describes what kind of body it will be. We use CircleShape. cc.p(0, 0) sets the centre of mass in body counted from (0.5, 0.5).
#5 Last step is to assign created PhysicsBody to PhysicsSprite (phNode) and add it to the controller.

3. Execute function
Add this line:

addPhysicsCircle();

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

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

	addWallsAndGround();
	addPhysicsCircle();
}

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

5. Experiments
Let’s see what happen when we change WALLS_ELASTICITY to 1 and our PhysicsSprite elasticity to 1:
part12
Yes, that’s perpetual motion :)

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