Micrified
Micrified

Reputation: 3650

How to properly draw and remove circles in SpriteKit

In my App, I need to draw a circle. It is done as follows:

// Create the Shape Node
SKShapeNode *shape = [[SKShapeNode alloc]init];

CGFloat radius = 10;

// Draw Shape Path
CGMutablePathRef myPath = CGPathCreateMutable();
CGPathAddArc(myPath, NULL, 0, 0, radius, 0, M_PI*2, YES);
[shape setPath:myPath];
[shape setLineWidth:1.0];

// Set Properties, Hierarchy, and add to scene
SKSpriteNode *sprite = [[SKSpriteNode alloc]init];
[sprite addChild:shape];

Cool. I just create an SKShapeNode, set it's Path, then add it as the child of a sprite.

To remove this later, I do as follows:

SKShapeNode *shape = (SKShapeNode *)[self.parentNode childNodeWithName:@"shape"];
    [shape setPath:nil];

I also remove 'shape' from it's parent, and then Nullify it's parent to try and get rid of it.

But. This. Does. Not. Work.

Inside the simulator, the circle always disappears. But on a device, it stays onscreen and can't be removed. How do I remove it?

I literally null the 'path' property, null the 'shape' object, null its parent object, and it won't go away..

This is my issue at the moment.

Upvotes: 1

Views: 359

Answers (1)

0x141E
0x141E

Reputation: 12753

Instead of creating a CGPath to create a circle node, you can use the shapeNodeWithCircleOfRadius convenience method. For example,

CGFloat radius = 10;

SKShapeNode *shape = [SKShapeNode shapeNodeWithCircleOfRadius:radius];
// Give the shape a name (missing from your code)
shape.name = @"circle";

You can then access and remove the circle from the scene with

SKShapeNode *shape = (SKShapeNode *)[self childNodeWithName:@"circle"];
[shape removeFromParent];

where self is an SKScene subclass, such as GameScene.

Upvotes: 1

Related Questions