Search code examples
iosmacossprite-kitskphysicsbodycgpath

How to create a path for a labyrinth with physics body in SpriteKit


I want to create a labyrinth for my SpriteKit Game, but I have problems setting up the correct physics body. Take a look at this example:

example

blue : CGPath

green : labyrinth (CGPath linewidth=10)

red : physics body I want to create

I tried to draw the labyrinth with CGPath and SKShapeNode, but how can I set up the physics body for the inner bounds of my labyrinth?

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 38, 266);
CGPathAddLineToPoint(path, NULL, 37, 23);
CGPathAddLineToPoint(path, NULL, 127, 22);
CGPathAddLineToPoint(path, NULL, 127, 184);
CGPathAddLineToPoint(path, NULL, 273, 185);
CGPathAddLineToPoint(path, NULL, 273, 98);
CGPathAddLineToPoint(path, NULL, 274, 184);
CGPathAddLineToPoint(path, NULL, 127, 184);
CGPathAddLineToPoint(path, NULL, 127, 23);
CGPathAddLineToPoint(path, NULL, 364, 23);
CGPathAddLineToPoint(path, NULL, 364, 266);
CGPathCloseSubpath(path);
SKShapeNode *labyrinth = [SKShapeNode shapeNodeWithPath:path];
labyrinth = [SKColor greenColor];
labyrinth.lineWidth = 10;
[self addChild:labyrinth];

.

labyrinth.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromPath:path];

does not work. I need an option to include the line width of my path for the physics body.

Any suggestions or other options to implement a labyrinth like this?


Solution

  • thanks @primaryartemis! with your suggestion i created the following code:

            for (int i=0; i< [points_array count]-1; i++) {
                  // first point
                  CGPoint p1 = CGPointMake(points_array[i].x, points_array[i].y);
                  // second point                  
                  CGPoint p2 = CGPointMake(points_array[i+1].x, points_array[i+1].y);
                  // midpoint
                  CGPoint p3 = CGPointMake(p1.x-p2.x, p1.y-p2.y);
    
                  float angle = atanf(p3.y/p3.x);
                  NSInteger length = sqrt(p3.x*p3.x + p3.y*p3.y);
    
                  SKSpriteNode *frameElement = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(length+10, 10)];
                  frameElement.zRotation = angle;
                  frameElement.position = CGPointMake(p1.x-p3.x/2, p1.y-p3.y/2);
    
                  frameElement.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:frameElement.size];
                  [self addChild:frameElement];
            }
    

    it works. Here is a sample output: (red is the physics body, blue is the midpoint)

    enter image description here