Create a line with two CGPoints SpriteKit Swift

后端 未结 4 1100
名媛妹妹
名媛妹妹 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:01

    This can be done using CGPath and SKShapeNode.

    Lets start with CGPath. CGPath is used when we need to construct a path using series of shapes or lines. Paths are line connecting two points. So to make a line:

    1. moveToPoint: It sets the current point of the path to the specified point.
    2. addLineToPoint: It draws a straight line from the current point to the specified point. or addCurveToPoint: It draws a curved line from the current point to the specified point based on certain tangents and control points.

    You can check the documentation here: http://developer.apple.com/library/mac/#documentation/graphicsimaging/Reference/CGPath/Reference/reference.html

    What you need to do is:

        var path = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, 100, 100)
        CGPathAddLineToPoint(path, nil, 500, 500)
    

    Now to make the path visible, and give it attributes like stroke color, line width etc. you create a SKShapeNode in SpriteKit and add the path to it.

        let shape = SKShapeNode()
        shape.path = path
        shape.strokeColor = UIColor.whiteColor()
        shape.lineWidth = 2
        addChild(shape)
    

    Hope this helps :).

提交回复
热议问题