Cocos2d Chipmunk: Touch Shapes?

899 views Asked by At

Today i got a cocos2d question!

I got a few shapes and the space-manager set up in my .m file by using nodes:

- (CCNode*) createBlockAt:(cpVect)pt

                    width:(int)w
                   height:(int)h
                     mass:(int)mass
{
    cpShape *shape = [smgr addRectAt:pt mass:mass width:w height:h rotation:0];

    cpShapeNode *node = [cpShapeNode nodeWithShape:shape];
    node.color = ccc3(56+rand()%200, 56+rand()%200, 56+rand()%200);

    [self addChild:node];

    return node;
}

- (CCNode*) createCircleAt:(cpVect)pt
                     mass:(int)mass
                     radius:(int)radius
{
    cpShape *shape = [smgr addCircleAt:pt mass:mass radius:radius];
    cpShapeNode *node1 = [cpShapeNode nodeWithShape:shape];
    CCSprite *sprt = [CCSprite spriteWithFile:@"fire.png"];
    node1.color = ccc3(56+rand()%200, 56+rand()%200, 56+rand()%200);

    [self addChild:node1];

    return node1;
}

then i actually make the shapes, set up a background, alloc and start the space-manager in my init method:

- (id) init
{
    [super init];

    CCSprite *background = [CCSprite spriteWithFile:@"BGP.png"];
    background.position = ccp(240,160);
    [self addChild:background]; 

    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];

    //allocate our space manager
    smgr = [[SpaceManagerCocos2d alloc] init];
    smgr.constantDt = 1/55.0; 

    [smgr addWindowContainmentWithFriction:1.0 elasticity:1.0 inset:cpvzero];

    [self createBlockAt:cpv(160,50) width:50 height:100 mass:100];
    [self createBlockAt:cpv(320,50) width:50 height:100 mass:100];
    [self createBlockAt:cpv(240,110) width:210 height:20 mass:100];
    [self createCircleAt:cpv(240,140) mass:25 radius:20];

    [smgr start];

    return self;
}

Now, i want a shape to be removed if it's touched. What is the best way to do that??? I hope that somebody out there can help me :)

Edit: Plz somebody, start a bounty! Or i never get this answered :(

-DD

1

There are 1 answers

7
Kazuki Sakamoto On BEST ANSWER

How about like this?

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint point = [self convertTouchToNodeSpace:touch];
    cpShape *shape = [smgr getShapeAt:point];
    if (shape) {
        [self removeChild:shape->data cleanup:YES];
        [smgr removeAndFreeShape:shape];
    }
    return YES;
}