ios - 从 Sprite 拖一条直线到 SpriteKit 中的手指位置

标签 ios swift sprite-kit

我想知道问题是否与节点的排列有关,而不是与代码有关,但我似乎无法让这条线正常工作。我想从触摸的节点到触摸的位置绘制一条可拖动的直线。然后该节点将移动到触摸结束的位置。我的代码基于我在这里看到的一些内容,但仍然无法显示出来。此相关节点是 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)

关于ios - 从 Sprite 拖一条直线到 SpriteKit 中的手指位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381237/

相关文章:

ios - UIView 挥动 ARM

ios - 寻找 View 的中心

ios - CollectionView 标题中的标签问题

ios - 拖动通过 SKPhysicsJoints 连接的 Sprite 的最佳方式?

swift - Node的路径粒子效果与SpriteKit

ios - SpriteKit 检测多次碰撞而不是一次(Swift 3)

ios - 缺少 DSYM 以处理崩溃

ios - UITableView : select row with checkmark but no highlight

ios - 如何使用可绑定(bind)对象(EnvironmentObject)?

ios - 否定#available语句