Page 1 of 1

How to implement simple pendulum?

Posted: Thu Oct 29, 2009 1:14 am
by Aurigan
Hi, I'm just getting started using chipmunk for the first time and am trying to build a simple pendulum, also using cocos2d. what would the recommended method for this be? My first attempt at this was to do the below, this results in the rope and the weight/box bouncing about all over the place manically.

create a static body:

Code: Select all

	staticBody = cpBodyNew(INFINITY, INFINITY);
	staticBody->p = cpv(0, 0);
add a 'rope' and pivotJoint this to the static body:

Code: Select all

	cpVect rope_verts[] = {
		cpv(-5,-70),
		cpv(-5, 70),
		cpv( 5, 70),
		cpv( 5,-70),
	};
	
	cpFloat mass = 1;
	ropeBody = cpBodyNew(mass, cpMomentForPoly(mass, 4, rope_verts, cpvzero));
	ropeBody->p = cpv(240, 250);
	cpSpaceAddBody(space, ropeBody);	

	cpShape *ropeShape = cpPolyShapeNew(ropeBody, 4, rope_verts, cpvzero);
	ropeShape->e = 0.0;
	ropeShape->u = 0.8;
	ropeShape->data = ropeSprite;
	ropeShape->collision_type = 1;
	cpSpaceAddShape(space, ropeShape);

	cpSpaceAddJoint(space, cpPivotJointNew(staticBody, ropeBody, cpv(240,320)));	

add a 'box' and pivot joint it to the rope:

Code: Select all

 	cpVect box_verts[] = {
		cpv(-100,-90),
		cpv(-100, 90),
		cpv( 100, 90),
		cpv( 100,-90),
	};	
	
	cpFloat mass = 50.0;
	boxBody = cpBodyNew(mass, cpMomentForPoly(mass, 4, box_verts, cpvzero));
	boxBody->p = cpv(240, 160);
	cpSpaceAddBody(space, boxBody);
	
	cpShape *boxShape = cpPolyShapeNew(boxBody, 4, box_verts, cpvzero);	
	boxShape->e = 0.5;
	boxShape->u = 0.8;
	boxShape->data = boxSprite;
	boxShape->collision_type = 1;
	cpSpaceAddShape(space, boxShape);	

	cpSpaceAddJoint(space, cpPivotJointNew(boxBody, ropeBody, cpv(240,180)));
is this a sensible way to try to do this? if so what am i doing wrong? if not, what is? the eventual aim is to introduce objects to 'hit' the pendulum to get it to swing. thanks!

Re: How to implement simple pendulum?

Posted: Thu Oct 29, 2009 6:16 pm
by Aurigan
solved this myself ... the bodies were colliding and jointed together in a way that kept them colliding. moving the bodies apart slightly and putting the joint in between keeps them stable.