在我觸摸某個精靈物件后,我試圖讓一條直線跟隨我的手指。到目前為止,我一直在作業,除了不是繪制一條線,而是在觸摸后繪制無限條線......
我的代碼:
import SpriteKit
import GameplayKit
class WireDrawTest: SKScene{
var drawingLayer: CAShapeLayer!
var redBox = SKSpriteNode()
var redBoxPoint = CGPoint(x: 445, y: 800)
var redBoxTouched:Int = -1
var currentTouch = touchesMoved
func drawLine(from: CGPoint, to: CGPoint) {
let line = SKShapeNode()
let path = CGMutablePath()
path.addLines(between: [from, to])
line.path = path
line.strokeColor = UIColor.yellow
line.lineWidth = 13
addChild(line)
}
override func didMove(to view: SKView) {
redBox = self.childNode(withName: "redBox") as! SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print(redBoxTouched)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in: self){
let nodesArray = self.nodes(at: location)
if nodesArray.first?.name == "redBox" {
if redBoxTouched == -1 {
redBoxTouched = 1
}
}
if redBoxTouched == 1 {
drawLine(from: redBoxPoint, to: location)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print(redBoxTouched)
if redBoxTouched == 1 {
redBoxTouched = -1
}
}
}
這是當前結果的截圖: 截圖
蒂亞!!
uj5u.com熱心網友回復:
每次呼叫 時drawLine,都會創建一個新的形狀節點并將其添加到場景中。但是,您永遠不會洗掉這些形狀節點中的任何一個,因此隨著您移動手指,線條數會增加。
一種解決方法是使用一個可選的形狀節點來記住上一行(如果有)。如果觸摸移動時有一個形狀節點,則只需洗掉并丟棄前一個形狀節點。當觸摸結束時,洗掉線。
或者,您可以創建一個形狀節點并在觸摸開始時將其添加到場景中,在觸摸移動時更改其路徑,并在觸摸結束時將其從場景中移除。如果我沒記錯的話,形狀節點會在內部復制路徑,因此僅具有可變路徑并更改路徑不會更新形狀節點。但我相信你可以創建一個新路徑并分配給形狀節點的path屬性來更新節點。
uj5u.com熱心網友回復:
由于 bg2b 使我走上了正確的軌道,我找到了解決方案...
首先,'let line = SKShapeNode' 不是包含在 drawWire 函式內部,而是需要在它之外,在主場景設定中。
從那里我剛剛添加了 'line.removeFromParent' 到 touchesEnded。現在它起作用了!我不知道為什么這有效,但確實如此!哈哈!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/337921.html
標籤:迅速 代码 精灵套件 skshapenode
