Objective-C SpriteKit - 如何制作按钮圈

时间:2015-11-04 18:22:33

标签: ios objective-c button sprite-kit geometry

我已经在项目中有一些代码,但我想稍微改变一下。目前,我的代码创建了一个名为_buttonLayer的空节点,然后创建一些添加到其中的按钮。我的按钮从_buttonLayer的左上角开始,然后一直添加到右下角。

// Set up button layer.
_buttonLayer = [SKNode node];
_buttonLayer.position = CGPointMake(_centerOfScreen.x - (_buttonSize.width * 1.5) - 5.0,
                                    self.size.height - ((self.size.height * 0.375) + (_buttonSize.height) - 50.0) + 5.0);
[self addChild:_buttonLayer];


// Set up button array.
_buttonArray = [NSMutableArray array];


// Add some buttons.
for (char row = 0; row < 4; row++) {
    for (char col = 0; col < 4; col++) {

        // Buttons.
        SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:@"LightGreyButton"];
        button.name = @"LightGreyButton"; // Initially set it to grey, because they all start off that way.
        button.size = _buttonSize;
        button.position = CGPointMake(2.0 + ((button.size.width + 3.0) * col),
                                      -(2.0 + ((button.size.height + 3.0) * row)));
        [_buttonLayer addChild:button];
        [_buttonArray addObject:button];

    }
}

所以我现在需要做的是创建一个圆形的按钮 - 而不是一个正方形。我想以某种方式将按钮添加到圆圈的轮廓中,然后取整个_buttonLayer并旋转它。当然,我现在拥有它的方式,它在广场的左上角旋转。我希望圆圈的中间旋转。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:2)

for循环更改为:

int numberOfButtons = 4; // The number of buttons you want.
int radiusOfCircle = button.size.width*4; // The radius of the circle that will contain those buttons.

for (int i = 0; i < numberOfButtons; i++) {

    // Buttons.
    SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:@"LightGreyButton"];
    button.name = @"LightGreyButton"; // Initially set it to grey, because they all start off that way.
    button.size = _buttonSize;
    CGFloat angle = 2*M_PI/numberOfButtons * i;
    button.position = CGPointMake(radiusOfCircle*cos(angle),radiusOfCircle*sin(angle));
    [_buttonLayer addChild:button];
    [_buttonArray addObject:button];
}

此外,正如Darvydas建议的那样,如果您要围绕某个sprite轮播CGPoint centerOfRotation,请设置sprite.anchorPoint = centerOfRotation;

请记住,我在没有测试的情况下编写了这个(我现在更习惯使用Swift而不是Objective-C)。但我认为它应该有效......是吗? :)

答案 1 :(得分:0)

要使节点轮换而不是SKSpriteNode,您应该使用SKShapeNode

SKShapeNode* button = [SKShapeNode node];
[button setPath:CGPathCreateWithRoundedRect(CGRectMake(-50, -50, 100, 100), 50, 50, nil)];

使按钮填充不可见

    button.fillColor = [UIColor clearColor];

更改轮廓宽度

    button.lineWidth = 100

更多信息: https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKShapeNode_Ref/index.html

将中心设置anchorPoint周围的节点旋转到节点中心