Search code examples
iosswiftsprite-kitskshapenode

Drawing a Line that Changes Direction


I currently am attempting to make an app that consists of a line that goes straight up, but when the screen is tapped it changes at a 45 degree angle (To the left or right).

I'm creating the path for this like so:

        var path = CGPathCreateMutable()
    for var i = 0; i < wayPoints.count; i++ {
        let p = wayPoints[i]
        if i == 0 {
            CGPathMoveToPoint(path, nil, p.x, p.y)
        } else {
            CGPathAddLineToPoint(path, nil, p.x, p.y)
        }
    }

And I populate the wayPoints array like so (This chunk of code is called a few times every second):

        if (wayPoints.isEmpty) {
        wayPoints.append(CGPointMake(0, CGRectGetMinY(self.view!.frame)))
    } else {
        if (wayPoints.count >= 30) {
            while (wayPoints.count >= 30) {
                wayPoints.removeAtIndex(0)
            }
        }
        if (currentPosition == Position.Right) {
            wayPoints.append(CGPointMake(wayPoints.last!.x + 1, wayPoints.last!.y + 1))
        } else if (currentPosition == Position.Left) {
            wayPoints.append(CGPointMake(wayPoints.last!.x - 1, wayPoints.last!.y + 1))
        } else {
            wayPoints.append(CGPointMake(0, wayPoints.last!.y + 1))
        }
    }

(The currentPosition changes when a tap occurs).

And although I don't think this matters, this is how I'm creating the SKShapeNode line:

let shapeNode = SKShapeNode()
shapeNode.path = path
shapeNode.name = "line"
shapeNode.strokeColor = UIColor.blackColor()

This somewhat works, but for some reason it seems as if there is a "leak" (not memory) in the path. This is what it looks like with the above code: http://gyazo.com/92dd84de15e125ea3d598cbfa9a86b13

As you can see, it makes almost a triangle when the line turns. It should just be a line without all that excess 'mass' on the sides.


Solution

  • The triangle you see is the line path being filled with a color. In this case, black. To remedy this, set the fillColor property of the shape node to the invisible color by

    shapeNode.fillColor = SKColor.clearColor()
    

    I used SKColor here instead of UIColor because the former can be used, without modification, in both Mac OS X and iOS apps.