【问题标题】:SKSpriteNode does not get updatedSKSpriteNode 未更新
【发布时间】:2018-03-22 22:42:44
【问题描述】:

我只是想让 spritenode 在被点击时移动。但似乎场景不会更新,直到第二次点击另一个 spritenode 点击发生。

我的错误在哪里?

override init(size: CGSize) {
    super.init(size: size)
    cardLayer = SKNode()
    addChild(cardLayer)
    sprite = SKSpriteNode()
    let cardSize = CGSize(width: 80,height: 100)
    sprite.size = cardSize
    sprite.texture = SKTexture(imageNamed: "1.png")
    sprite.position = CGPoint(x: 200, y: 200)
    sprite.name = "123"
    cardLayer.addChild(sprite)
    sprite1 = SKSpriteNode()
    sprite1.size = cardSize
    sprite1.texture = SKTexture(imageNamed: "1.png")
    sprite1.position = CGPoint(x: 200, y: 300)
    sprite1.name = "123"
    cardLayer.addChild(sprite1)
}




override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let array = Array(touches)
    let touch = array[0] 
    let location = touch.location(in: self)
    let touchedNode = atPoint(location)
    if let _ = touchedNode.name {
        print("moved")
        touchedNode.position = CGPoint(x: 10, y: 10)
    }
}

【问题讨论】:

  • 按照 if let _ = touchNode.name {
  • 能否请您说明您所说的“继续工作”是什么意思。该节点有一个名称,所以在我看来这条线是正确的。我的问题是仅更改位置不会更新节点。为什么呢? (如果我在这里添加一个动作就可以了,但这只是一个例子——最后我有一个函数可以更新超过 50 个节点的位置和图像)
  • 向谷歌或擅长搜索引擎搜索的人询问节点名称。
  • 对不起,“问谷歌”真的没有帮助。

标签: swift skspritenode


【解决方案1】:

这就是我做你想做的事情的方式。

我认为您应该尝试使用 nodes(at: )

这是一个使用的例子

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


if let touch = touches.first {
//gets location
            let location = touch.location(in: self)
//gets of what nodes are at the location
            let object = nodes(at: location)
// if the there is a node on that location that is the sprite I want
            if object.contains(yourSprite){
//you can put what ever numbers you want to run in there. This simply
// determines the direction of the movement based on a t-Graph
                yourSprite.run(SKAction.moveBy(x: 0, y: -5, duration: 1))
            }
}

【讨论】:

  • nodes(at:) 只是 Swift 3 版本的 location(in:)。
  • 我刚刚检查了我的代码,它工作得非常好,它确实完成了你想要做的事情。
  • 你的代码工作的原因是 yourSprite.run(SKAction.moveBy(x: 0, y: -5, duration: 1)) 而不是节点(at:)。 nodes(at:) 已在较新的 Swift 版本中重命名。但我需要在不执行动画的情况下更新 Sprite……如果可能的话。
  • 我正在运行最新版本的 Xcode,所以我不知道你在说什么更新。这也不是它起作用的“原因”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-23
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多