Search code examples
cocos2d-iphonegame-physicschipmunk

How to make a physical wall using cocos2d / chipmunk?


How to make a physical wall using cocos2d / chipmunk ? So that sprite just can not go throught another one sprite(wall)? Sorry,if it's already answered somewhere, I can't find any information for beginners.


Solution

  • This is from cocos2d/chipmunk template. Your sprite should be on chipmunk body, to get that change position of sprite to position of body in your update method.

    CGSize s = [[CCDirector sharedDirector] winSize];
    
    _space = cpSpaceNew();
    
    cpSpaceSetGravity( _space, cpv(0, -100) );
    
    //
    // rogue shapes
    // We have to free them manually
    //
    // bottom
    _walls[0] = cpSegmentShapeNew( _space->staticBody, cpv(0,0), cpv(s.width,0), 0.0f);
    
    // top
    _walls[1] = cpSegmentShapeNew( _space->staticBody, cpv(0,s.height), cpv(s.width,s.height), 0.0f);
    
    // left
    _walls[2] = cpSegmentShapeNew( _space->staticBody, cpv(0,0), cpv(0,s.height), 0.0f);
    
    // right
    _walls[3] = cpSegmentShapeNew( _space->staticBody, cpv(s.width,0), cpv(s.width,s.height), 0.0f);
    
    for( int i=0;i<4;i++) {
        cpShapeSetElasticity( _walls[i], 1.0f );
        cpShapeSetFriction( _walls[i], 1.0f );
        cpSpaceAddStaticShape(_space, _walls[i] );
    }