【发布时间】:2014-07-22 16:05:28
【问题描述】:
大家好,我正在制作一个 sprite-kit 应用程序,用户必须能够在其中绘制多条线。为此,我编写了以下代码。
import SpriteKit
class GameScene: SKScene {
var line = SKShapeNode()
var path = CGPathCreateMutable()
var touch: UITouch!
var location:CGPoint!
override func didMoveToView(view: SKView) {
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
touch = touches.anyObject() as UITouch!
location = touch.locationInNode(self)
drawLine()
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
self.delete(line)
}
func drawLine() {
CGPathMoveToPoint(path, nil, location.x, location.y)
CGPathAddLineToPoint(path, nil, 500.0, 500.0)
line.path = path
line.strokeColor = UIColor.redColor()
line.lineWidth = 5.0
self.addChild(line)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
这可行,但是当用户尝试绘制第二行时,应用程序崩溃了。 有人可以向我解释为什么会这样吗?
-----编辑-----
我认为我需要使用一系列行,所以我做了这样的事情:
var line: [[SKShapeNode]] = []
这给了我以下错误: [[SKShapeNode]] 没有名为“路径”的成员。 因此,尽管我也必须将路径变量设为数组,但这只会给我第二个错误:GameScene 没有名为“路径”的成员。所以我把它全部改回来了,但我仍然认为我必须使用一个数组,尽管我真的不知道如何让它工作。
【问题讨论】:
-
第二次调用 drawLine 时,您添加了两次相同的节点(线)。如果您想同时绘制两者,则必须在调用 drawLine 时创建一个新的 SKShapeNode 实例,或者只需更改线条的路径以更新现有线条的路径。
-
所以最好的方法是使用数组,但我该如何实现呢?
-
你对理解数组世界的探索,不是这个问题的主题。谷歌“Swift Arrays”——互联网是你的朋友。 :)
标签: xcode swift sprite-kit