user2331875
user2331875

Reputation: 134

Update SKShapeNode that is attached to SKNode

I am trying to modify SKShapeNode that I already added to SKNode.

This is my code for adding SKNode to the screen and attaching SKShapeNode to it. Now I am trying to modify color of that specific SKShapeNode, but I am not sure how to do it. Any advice?

SKNode *dot = [SKNode node];

SKShapeNode *circle = [SKShapeNode node];
circle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 20, 20)].CGPath;
circle.fillColor = [UIColor blueColor];
circle.strokeColor = [UIColor blueColor];
circle.glowWidth = 5;
[dot addChild:circle];

[self addChild:dot];

Upvotes: 3

Views: 1676

Answers (2)

Andrey Gordeev
Andrey Gordeev

Reputation: 32449

Make SKShapeNode a property of your SKScene:

@interface YourScene()
@property SKShapeNode *circle;
@end

Change the code which creates the circle to this:

self.circle = [SKShapeNode node];
self.circle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 20, 20)].CGPath;
self.circle.fillColor = [UIColor blueColor];
self.circle.strokeColor = [UIColor blueColor];
self.circle.glowWidth = 5;
[dot addChild:self.circle];

Now you can access circle node anywhere in the scene:

- (void)changeColor {
    self.circle.fillColor = [SKColor redColor];
}

Another option is to give the node a name:

SKShapeNode *circle = [SKShapeNode node];
.....
circle = @"circle";

And access that node by name

- (void)changeColor {
    // Assuming the dot node is a child node of the scene
    SKShapeNode *circle = (SKShapeNode*)[self.scene childNodeWithName:@"/circle"];
    circle.fillColor = [SKColor redColor];
}

Upvotes: 2

user3029120
user3029120

Reputation: 34

try to remove all children and readd new child

[dot removeAllChildren];
[dot  addChild:circle];

Upvotes: 2

Related Questions