如何在Sprite Kit中制作一个圆形或其他形状我见过一些使用CGPath的工具,但我从未真正使用过CGPath。我可以用SKSpritenode制作正方形,但似乎无法制作三角形或圆形。

最佳答案

这将创建一个SKShapeNode并将其path属性设置为半径为16的圆形路径。

    SKShapeNode *shape = [SKShapeNode node];
    CGRect rect = CGRectMake(0, 0, 32, 32);
    shape.path = [self circleInRect:rect];
    shape.strokeColor = [SKColor greenColor];
    shape.fillColor = [SKColor redColor];
    shape.position = CGPointMake(100,100);

    [self addChild:shape];


此方法返回以椭圆路径初始化的CGPath对象

- (CGPathRef) circleInRect:(CGRect)rect
{
    // Adjust position so path is centered in shape
    CGRect adjustedRect = CGRectMake(rect.origin.x-rect.size.width/2, rect.origin.y-rect.size.height/2, rect.size.width, rect.size.height);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithOvalInRect:adjustedRect];
    return bezierPath.CGPath;
}


这是一条三角形的路...

- (CGPathRef) triangleInRect:(CGRect)rect
{
    CGFloat offsetX = CGRectGetMidX(rect);
    CGFloat offsetY = CGRectGetMidY(rect);
    UIBezierPath* bezierPath = [UIBezierPath bezierPath];

    [bezierPath moveToPoint: CGPointMake(offsetX, 0)];
    [bezierPath addLineToPoint: CGPointMake(-offsetX, offsetY)];
    [bezierPath addLineToPoint: CGPointMake(-offsetX, -offsetY)];

    [bezierPath closePath];
    return bezierPath.CGPath;
}

08-17 01:12