我想知道问题是否与节点的排列有关,而不是与代码有关,但是我似乎无法使这一行正常工作。我想从触摸的节点到触摸的位置绘制一条可拖动的直线。然后,该节点将移动到结束触摸的位置。我的代码基于我在这里看到的一些内容,但仍然无法显示出来。此相关节点是SKSpriteNode
的子类,并且此代码位于该类中,而不是在主GameScene
类中。
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.childNode(withName: "line")?.removeFromParent() // Remove any previous line
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self.parent!) // Use 'parent' here?
let path = CGMutablePath()
let line = SKShapeNode(path: path) // Create shape node with path as path
line.name = "line"
line.zPosition = 5000 // Just trying to make sure it's on top
line.strokeColor = UIColor.red
line.lineWidth = 20
line.fillColor = UIColor.red
path.move(to: CGPoint(x: self.position.x, y: self.position.y))
path.addLine(to: CGPoint(x: positionInScene.x, y: positionInScene.y))
self.addChild(line)
}
当我在touchesBegan
中创建并添加路径时,它会显示出来,但是会画出一堆线,我只需要一个。
简单错误。绘制后只需将path
分配给该行。
let path = CGMutablePath()
path.move(to: CGPoint(x: self.position.x, y: self.position.y))
path.addLine(to: CGPoint(x: positionInScene.x, y: positionInScene.y))
let line = SKShapeNode(path: path) // Create shape node with path as path
self.addChild(line)