SKPhysicsBody Path Generator

时间:2015-03-30 17:11:47

标签: swift sprite-kit skphysicsbody

我正在使用SKPhysicsBody Path Generator

为我的精灵生成polygonFromPath。问题是我需要一个有两个孔的路径,我该如何实现呢?

如下图所示,路径最多只能与一个孔相连,但我需要两个孔!有什么帮助吗?

enter image description here

我也试过以下但它崩溃了:

let path = CGPathCreateMutable()

        MoveToPoint(path, x: 51 , y:22 , node:sprite)
        AddLineToPoint(path, x: 38 , y:45 , node:sprite)
        AddLineToPoint(path, x: 32 , y:44 , node:sprite)
        AddLineToPoint(path, x: 32 , y:0 , node:sprite)
        AddLineToPoint(path, x: 39 , y:0 , node:sprite)

        let path2 = CGPathCreateMutable()

        MoveToPoint(path2, x: 0 , y:22 , node:sprite)
        AddLineToPoint(path2, x: 13 , y:0 , node:sprite)
        AddLineToPoint(path2, x: 19 , y:0 , node:sprite)
        AddLineToPoint(path2, x: 19 , y:45 , node:sprite)
        AddLineToPoint(path2, x: 13 , y:45 , node:sprite)

sprite.physicsBody = SKPhysicsBody(bodies: [path, path2])

2 个答案:

答案 0 :(得分:0)

您不能将bodyWithPolygonFromPath用于您想要的形状。 bodyWithPolygonFromPath仅适用于凸多边形路径。

您可以使用bodyWithBodies:(NSArray *)bodies在右侧和底侧绘制2个三角形,在左上角绘制正方形。请记住,空白区域不会注册联系人。

以下是一个例子:

SKSpriteNode node0 = [SKSpriteNode spriteNodeWithColor:[SKColor lightGrayColor] size:CGSizeMake(200, 200)];
node0.position = CGPointMake(400, 400);

SKPhysicsBody *firstBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(50, 50) center:CGPointMake(-75, 75)];
SKPhysicsBody *secondBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(200, 50) center:CGPointMake(0, -75)];
SKPhysicsBody *thirdBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(50, 150) center:CGPointMake(75, 26)];
node0.physicsBody = [SKPhysicsBody bodyWithBodies:@[firstBody, secondBody, thirdBody]];
node0.physicsBody.dynamic = NO;
[self addChild:node0];

答案 1 :(得分:0)

好的,我解决了它:)

让sprite = SKSpriteNode(imageNamed:“cell3”)

sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

let path = CGPathCreateMutable()

MoveToPoint(path, x: 51 , y:22 , node:sprite)
AddLineToPoint(path, x: 38 , y:45 , node:sprite)
AddLineToPoint(path, x: 32 , y:44 , node:sprite)
AddLineToPoint(path, x: 32 , y:0 , node:sprite)
AddLineToPoint(path, x: 39 , y:0 , node:sprite)

CGPathCloseSubpath(path)

let path2 = CGPathCreateMutable()

MoveToPoint(path2, x: 0 , y:22 , node:sprite)
AddLineToPoint(path2, x: 13 , y:0 , node:sprite)
AddLineToPoint(path2, x: 19 , y:0 , node:sprite)
AddLineToPoint(path2, x: 19 , y:45 , node:sprite)
AddLineToPoint(path2, x: 13 , y:45 , node:sprite)

CGPathCloseSubpath(path2)

let b1 = SKPhysicsBody(polygonFromPath: path)

let b2 = SKPhysicsBody(polygonFromPath: path2)

sprite.physicsBody = SKPhysicsBody(bodies: [b1, b2])