Create a line with two CGPoints SpriteKit Swift

后端 未结 4 1096
名媛妹妹
名媛妹妹 2021-02-08 01:47

I am trying to make a simple app where you touch a point, and a sprite follows a line through that point to the edge of the screen, no matter where you touch. I want to draw lin

4条回答
  •  隐瞒了意图╮
    2021-02-08 02:18

    For the sake of simplicity, I pulled everything necessary to draw a line into an extension of SKShapeNode that allows you to create a line with a start & end point, as well as a strokeColor and strokeWidth (you could always preset these or make default values should you choose too)

    extension SKShapeNode {
        convenience init(start: CGPoint,
                         end: CGPoint,
                         strokeColor: UIColor,
                         lineWidth: CGFloat) {
            self.init()
    
            let path = CGMutablePath()
            path.move(to: start)
            path.addLine(to: end)
    
            self.path = path
            self.strokeColor = strokeColor
            self.lineWidth = lineWidth
        }
    }
    

    The basic idea is that it will create a CGMutablePath with the provided points and assign it to the shape node for drawing a line.

    To call it:

    let horizontalLine = SKShapeNode(start: CGPoint(x: 0, y: 50),
                                     end: CGPoint(x: size.width, y: 50),
                                     strokeColor: .orange,
                                     lineWidth: 2.0)
    addChild(horizontalLine)
    

    And the output:

提交回复
热议问题