iDev/Cocos2D

cocos2d v3에서 collision detection 하기

KraZYeom 2014. 3. 2. 03:05
반응형

cocos2d v3에는 기본적으로 Chimpunk가 내장되어 있다. 충돌을 했을 때 이벤트 처리를 하기 위해서 이리저리 삽질하다가 알아낸 결과. 이상하게 구글링을 해도 제대로된게 안나온다. 


헤더 파일에 자세하게 나와있는데 감이 안오다가. 구현하고 나서 헤더 파일을 보니 이제야 알겠음.


physicsBody에서 collisionGroup이 같으면 같은놈으로 취급하여 충돌시키지 않는다. 반대로 생각해서 계속해서 통과해서 오랜시간 삽질. 기본적으로 nil값으로 무조건 충돌시킨다. 


가장중요한건 collisionType. collisionType 에 부여된 이름에 따라서 delegate에서 호출하는 메소드 명이 달라진다. 여기서도 오랜시간 삽질. 기본값은 default 이다. 하지만 ccPhysicsCollisionBegin:typeA:typeB로 되어 있어서 삽질. 

ccPhysicsCollisionBegin:default:default 로 변경을 하거나 아니면 collisionType 에 부여된 이름처럼 아래와 같이 메소드 명을 변경한다. 



@interface GameScene : CCScene <CCPhysicsCollisionDelegate>


  _physics.collisionDelegate = self;


  water.physicsBody.collisionType = @"water";

  leap.physicsBody.collisionType = @"leap";

  frog.physicsBody.collisionType = @"frog";


-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair typeA:(CCNode *)nodeA typeB:(CCNode *)nodeB{

  return YES;

}



-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair water:(CCNode *)nodeA frog:(CCNode *)nodeB{

  CCLOG(@"collison frog");

  return YES;

}


-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair frog:(CCNode *)nodeA leap:(CCNode *)nodeB{

  CCLOG(@"collison leap");

//  [nodeB removeFromParent];

  return YES;

}




이건 헤더 파일의 일부분. 

/**

 *  Is this body a sensor? A sensor will call a collision delegate but does not physically cause collisions between bodies.

 *  Defaults to NO.

 */

@property(nonatomicassignBOOL sensor;


/**

 *  The body's collisionGroup, if two physics bodies share the same group id, they don't collide. Defaults to nil.

 */

@property(nonatomicassignid collisionGroup;


/**

 *  A string that identifies the collision pair delegate method that should be called. Default value is @"default".

 */

@property(nonatomiccopyNSString *collisionType;


/**

 *  An array of NSString category names of which this physics body is a member. Up to 32 unique categories can be used in a single physics node.

 *  A value of nil means that a body exists in all possible collision categories.

 *  The deefault is nil.

 */

@property(nonatomiccopyNSArray *collisionCategories;


/**

 *  An array of NSString category names that this physics body wants to collide with.

 *  The categories/masks of both bodies must agree for a collision to occur.

 *  A value of nil means that this body will collide with a body in any category.

 *  The default is nil.

 */

@property(nonatomiccopyNSArray *collisionMask;



반응형