简体   繁体   English

用两个 CGPoints SpriteKit Swift 创建一条线

[英]Create a line with two CGPoints SpriteKit Swift

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 line segments connecting the origin of the sprite (point where it starts) and the point where you touched, and between the origin of the sprite and the end point at the edge of the screen, so I can visualize the path of the sprite and the relationship between the x and y offsets of the origin, touch point and end point.我想绘制连接精灵的原点(它开始的点)和你触摸的点,以及精灵的原点和屏幕边缘的终点之间的线段,这样我就可以形象化sprite 以及原点、触摸点和终点的 x 和 y 偏移量之间的关系。

Hopefully that was not too confusing.希望这不会太令人困惑。

TL;DR: I need to draw a line between two points and I don't know how to do that using SpriteKit Swift. TL;DR:我需要在两点之间画一条线,但我不知道如何使用 SpriteKit Swift 来做到这一点。

Thanks in advance.提前致谢。

This can be done using CGPath and SKShapeNode. 这可以使用CGPath和SKShapeNode完成。

Lets start with CGPath. 让我们从CGPath开始。 CGPath is used when we need to construct a path using series of shapes or lines. 当我们需要使用一系列形状或线条构造路径时,使用CGPath。 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. moveToPoint:它将路径的当前点设置为指定的点。
  2. addLineToPoint: It draws a straight line from the current point to the specified point. addLineToPoint:它从当前点到指定点绘制一条直线。 or addCurveToPoint: It draws a curved line from the current point to the specified point based on certain tangents and control points. 或者addCurveToPoint:它根据某些切线和控制点绘制从当前点到指定点的曲线。

You can check the documentation here: http://developer.apple.com/library/mac/#documentation/graphicsimaging/Reference/CGPath/Reference/reference.html 您可以在此处查看文档: 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. 现在,为了使路径可见,并为其提供描边颜色,线宽等属性,您可以在SpriteKit中创建一个SKShapeNode并添加路径。

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

Hope this helps :). 希望这可以帮助 :)。

Follow THIS tutorial step by step and you can achieve that. 按照教程逐步完成,您可以实现这一目标。

Consider the below code: 考虑以下代码:

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    let location = touches.anyObject()!.locationInNode(scene)
    if let pig = movingPig {
        pig.addMovingPoint(location)
    }
}

This is a simple method. 这是一种简单的方法。 You get the next position of the user's finger and if you found a pig in touchesBegan(_:,withEvent:) , as indicated by a non-nil movingPig value, you add the position to this pig as the next waypoint. 你得到了用户手指的下一个位置,如果你在touchesBegan(_:,withEvent:)找到了一只猪,如非零的movingPig值所示,你将该猪的位置添加为下一个航点。

So far, you can store a path for the pig—now let's make the pig follow this path. 到目前为止,你可以存储猪的路径 - 现在让我们让猪沿着这条路走。 Add the following code to update() inside GameScene.swift : 将以下代码添加到GameScene.swift update()

dt = currentTime - lastUpdateTime
lastUpdateTime = currentTime

enumerateChildNodesWithName("pig", usingBlock: {node, stop in
    let pig = node as Pig
    pig.move(self.dt)
})

And you can see result: 你可以看到结果:

在此输入图像描述

Drawing Lines: 绘图线:

At the moment, only the pig knows the path it wants to travel, but the scene also needs to know this path to draw it. 目前,只有猪知道它想要旅行的路径,但场景也需要知道这条路来画它。 The solution to this problem is a new method for your Pig class. 这个问题的解决方案是Pig类的一种新方法。

func createPathToMove() -> CGPathRef? {
    //1
    if wayPoints.count <= 1 {
        return nil
    }
    //2
    var ref = CGPathCreateMutable()

    //3
    for var i = 0; i < wayPoints.count; ++i {
         let p = wayPoints[i]

    //4
    if i == 0 {
        CGPathMoveToPoint(ref, nil, p.x, p.y)
    } else {
        CGPathAddLineToPoint(ref, nil, p.x, p.y)
     }
 }

 return ref
 }

this method to draw the pig's path: 这种绘制猪路径的方法:

func drawLines() {


//1
  enumerateChildNodesWithName("line", usingBlock: {node, stop in
    node.removeFromParent()
  })

  //2
  enumerateChildNodesWithName("pig", usingBlock: {node, stop in
    //3
    let pig = node as Pig
    if let path = pig.createPathToMove() {          
      let shapeNode = SKShapeNode()
      shapeNode.path = path
      shapeNode.name = "line"
      shapeNode.strokeColor = UIColor.grayColor()
      shapeNode.lineWidth = 2
      shapeNode.zPosition = 1

      self.addChild(shapeNode)
    }
  })
}

And here is your result: 这是你的结果:

在此输入图像描述

And you can set that path for the pig. 你可以设置猪的路径。

You can modify that as per your need. 您可以根据需要进行修改。

Hope it will help. 希望它会有所帮助。

For Swift 3, the CGPathMoveToPoint method doesn't like a nil for the second argument anymore, so I needed a new solution. 对于Swift 3, CGPathMoveToPoint方法不再喜欢第二个参数的nil ,所以我需要一个新的解决方案。 Here's what I came up with: 这是我想出的:

let line_path:CGMutablePath = CGMutablePath()
line_path.move(to: CGPoint(x:x1, y:y1))
line_path.addLine(to: CGPoint(x:x2, y:y2))

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)为简单起见,我将绘制一条线所需的一切都拉到SKShapeNode的扩展中,它允许您创建一条带有startend以及strokeColorstrokeWidth (您可以随时预设这些或设置默认值你也应该选择)

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.基本思想是它将使用提供的点创建一个 CGMutablePath 并将其分配给形状节点以绘制一条线。

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:和输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM