Search code examples
iossprite-kitskspritenodeskshapenode

SKShapeNode empty rectangle


I started to learn SpriteKit and immediatly run into a problem. I'm trying to draw an empty rectangle with a SKShapeNode but does appear on the screen. If i set a color to the fill property the rectangle appears. What am i doing wrong ?

    CGRect box = CGRectMake(0, 0, self.frame.size.width/2, self.frame.size.height/2);

    SKShapeNode *shapeNode = [[SKShapeNode alloc] init];
    shapeNode.path = [UIBezierPath bezierPathWithRect:box].CGPath;
    shapeNode.fillColor = nil;
    shapeNode.strokeColor = SKColor.redColor;
    shapeNode.lineWidth = 3;

    [self addChild:shapeNode];

Solution

  • Welcome to sprite kit, I am learning it as well and haven't had much experience with shapeNodes, but here is what I would suggest:

    //If you want the shape to be that of a rectangle I would suggest using a simpler allocation method such as the following:
    SKShapeNode *shapeNode = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(self.frame.size.width/2, self.frame.size.height/2))];
    
    /*shapeNodeWithRectOfSize is a built in allocation method for SKShapeNodes that handles
    allocation and initialization for you, and will also create the rectangle shape for you.
    The CGSizeMake method will return a CGSizeMake object for you*/
    
    /*a CGSizeMake object is an object with two properties: width, and height. It is used to hold
    the dimensions of objects. self.frame.size is a CGSize object*/
    
    /*You do not need to set the fill color to nil. This is because the default is [SKColor clearColor]
    which is an empty color already*/
    
    //Make sure that you use an initializer method when setting the colour as below
    shapeNode.strokeColor = [SKColor redColor];
    shapeNode.lineWidth = 3;
    
    [self addChild:shapeNode];
    

    If you would like a reference to the details of the SKShapeNode object then I would suggest looking here: Apple - SKShapeNode Reference

    If you would like a source of excellent quality tutorials I would suggest looking here:enter link description here

    I haven't tested the code as I am not able to at the moment, so let me know if it does not work and I will see what I can do to help you. Once again welcome to Sprite-Kit, I hope it is a pleasant experience.