请问您使用的哪一个物理引擎呢?关于这个教程的物理碰撞部分内容可以参考:https://github.com/chukong/CocoStudioSamples/blob/master/SampleCollision/Classes/TestColliderDetector.cpp
如box2d部分:
//! init physic world
b2Vec2 noGravity(0, 0);
world = new b2World(noGravity);
world->SetAllowSleeping(true);
listener = new ContactListener();
world->SetContactListener(listener);
debugDraw = new GLESDebugDraw( PT_RATIO );
world->SetDebugDraw(debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
// flags += b2Draw::e_jointBit;
// flags += b2Draw::e_aabbBit;
// flags += b2Draw::e_pairBit;
// flags += b2Draw::e_centerOfMassBit;
debugDraw->SetFlags(flags);
//! Define the dynamic body.
//! Set up a 1m squared box in the physics world
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
b2Body *body = world->CreateBody(&bodyDef);
//! Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
//define bullet's body shape
dynamicBox.SetAsBox(.5f, .5f);
//! Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.isSensor = true;
body->CreateFixture(&fixtureDef);
//! set body to bullet and add it to world
bullet->setB2Body(body);
bullet->setPTMRatio(PT_RATIO);
bullet->setPosition( ccp( -100, -100) );
body = world->CreateBody(&bodyDef);
armature2->setB2Body(body);
CHIPMUNK引擎:
//! create physic space
space = cpSpaceNew();
//! set space gravity as no gravity
space->gravity = cpv(0, 0);
//! Physics debug layer
CCPhysicsDebugNode *debugLayer = CCPhysicsDebugNode::create(space);
this->addChild(debugLayer, INT_MAX);
//! get size of bullet
CCSize size = bullet->getContentSize();
//! define bullet's collider body
int num = 4;
cpVect verts] = {
cpv(-size.width/2,-size.height/2),
cpv(-size.width/2,size.height/2),
cpv(size.width/2,size.height/2),
cpv(size.width/2,-size.height/2),
};
//! build body as verts' shape
cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));
cpSpaceAddBody(space, body);
cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero);
shape->collision_type = eBulletTag;
cpSpaceAddShape(space, shape);
bullet->setCPBody(body);
//! define armature2's body,get shape from armature data
body = cpBodyNew(INFINITY, INFINITY);
cpSpaceAddBody(space, body);
armature2->setBody(body);
shape = body->shapeList_private;
while(shape){
cpShape *next = shape->next_private;
shape->collision_type = eEnemyTag;
shape = next;
}
cpSpaceAddCollisionHandler(space, eEnemyTag, eBulletTag, beginHit, NULL, NULL, endHit, NULL);