Search code examples
swiftsprite-kitlinecgpathskshapenode

Draw straight line for aiming


If you played Angry Birds or any Pool game before you would be familiar with what I'm trying to do, basically what I want is:

1- Draw a line in touchesMoved so that the player can know in which direction he is aiming.

2- I want the line to reflect in the right direction when it hits other objects. So far I have this:

Update:

   var ref = CGPathCreateMutable()

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

            for touch in touches {
                let location = touch.locationInNode(self)

                let path = CGPathCreateMutable()
                CGPathMoveToPoint(ref, nil, position.x - 100 , position.y - 100 )
                CGPathAddLineToPoint(ref, nil, -location.x, -location.y)

                line.removeFromParent()
                line.path = ref

                line.strokeColor = UIColor.redColor()
                line.lineWidth = 20
                line.antialiased = true
                line.fillColor = UIColor.blueColor()
                addChild(line)
            }
        }

I added the - before location so that the line gets drawn in front of the node ao it gives better aiming sense, but that leave me with 2 problems:

1- I want the line to have a limit in which it gets in front of the node, but at the same time, I want its end to be the current touch location. ( Basically, I want it to go through the node)

2- I still don't know how can I make it reflect to the right angle when it hit a wall or something so it gives an idea of the node would bounce off that wall.


Solution

  • An alternative to deleting and adding a line node every frame, make a SKShapeNode of 1 pixel by 1 pixel, then scale on the x axis the distance of the from pt to the to pt, then rotate it. Use let angle = arctan2(P2_y - P1_y , P2_x - P1_x) (I believe arctan2 handles division by 0 for you) to get the angle