michaelsnowden
michaelsnowden

Reputation: 6202

How to detect collision without having collision take effect cocos2d

I have a game where kirby shoots basketballs into a net. The problem I am having is detecting whether a shot has scored. I set up the scene with the physics debug on, so all physics bodies are red. The red circle in the middle of the net is the body I use to detect whether a shot has scored. If a shot enters the circle, then it has scored. The problem is that I don't have a way for the shots to pass through the circle and still detect the collision. Scene

I tried this, which sets the ball to be a sensor as soon as it hits the circle, and a non-sensor as soon as it leaves the circle, letting it pass through but still hit the ground afterwards. The problem is that the initial collision still takes effect, so the ball bounces up a little and usually ends up hitting the circle two or three times.

- (void)ccPhysicsCollisionPostSolve:(CCPhysicsCollisionPair *)pair goal:(CCNode *)goal wildcard:(CCNode *)ball
{
    ball.physicsBody.sensor = YES;
}

- (void)ccPhysicsCollisionSeparate:(CCPhysicsCollisionPair *)pair goal:(CCNode *)goal wildcard:(CCNode *)ball
{
    ball.physicsBody.sensor = NO;
}

Upvotes: 1

Views: 610

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

It's quite simple if you use the other two collision delegate methods. In each you can determine whether a collision should occur, and if not return NO to tell Chipmunk to ignore the collision, allowing the bodies pass through each other.

- (BOOL)ccPhysicsCollisionPreSolve:(CCPhysicsCollisionPair *)pair 
                              goal:(CCNode *)goal
                              ball:(CCNode *)ball
{
    return NO;
}

- (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair
                           goal:(CCNode *)goal
                           ball:(CCNode *)ball
{
    return NO;
}

Upvotes: 1

Related Questions