首页 > 解决方案 > 以编程方式构建的节点上的 SKAction?如何定位节点?

问题描述

我之前对每个角色使用了单独的方法,并将它们写在每个场景文件中,但它既凌乱又庞大。

因此,为了清理代码,我编写了一个 buildCharater 方法来创建我在不同场景中需要的角色。如您所见,它还构建了相关的纹理图集和动画动作。但是,我需要让这些角色处于非活动状态 - 并且当被触摸时,动画会与其他动作一起开始。我能够使用 if let 切换可选名称来检测触摸,但我无法对如何在各个节点上调用操作进行排序 - 在此之前我能够执行 node.run(someAction) 但现在我迷路了如何定位单个节点以及使用关联的图集为它们设置动画。这是 buildCharacter 方法 -

func buildCharacter(name:String, height: CGFloat, width: CGFloat, position: CGPoint, zPosition: CGFloat) {
    let animatedAtlas = SKTextureAtlas(named: name)
    var animationFrames: [SKTexture] = []
    
    let numImages = animatedAtlas.textureNames.count
    for i in 1...numImages {
        let textureName = "\(name)\(i)"
        
        animationFrames.append(animatedAtlas.textureNamed(textureName))
    }
    
    animatedCharacter = animationFrames
    let firstFrameTexture = animatedCharacter[0]
    builtCharacter = SKSpriteNode(texture: firstFrameTexture)
    builtCharacter.size.height = height
    builtCharacter.size.width = width
    builtCharacter.position = position
    builtCharacter.zPosition = zPosition
    builtCharacter.name = name
    
    isUserInteractionEnabled = true
    addChild(builtCharacter)
    builtCharacters.append(builtCharacter)
    
    let animationAction = SKAction.repeatForever(SKAction.animate(with: animatedCharacter, timePerFrame: 0.1, resize: false, restore: true))
    builtCharacter.run(animationAction)
    
   }

我不想像现在那样立即运行动作——我希望能够通过开始触摸来启动和停止动作。

我之前为每个角色编写了一个动画方法,但我试图简化整个事情——对任何想法都开放!

谢谢

标签: sprite-kitskactionsknode

解决方案


您可以使用以下代码在您的触摸位置获取节点touchesBegan

  for t in touches {
    
    let location = t.location(in: self)
    let touchedNodes = self.nodes(at: location)
    
    for node in touchedNodes {
      let sprite = node as! SKSpriteNode
      sprite.run(animationAction)
    }
  }

这将在您的触摸位置找到的任何节点上运行动画。touchedNodes是一个数组,用于存储在您所在位置找到的所有节点。它们被存储起来,SKNode因此您可以SKSpriteNode在需要时将它们转换为。

您可以在其中添加一个if语句for node..来检查node.name,然后您可以根据您选择的节点运行特定的动画。在您的评论示例中,如果您单击 character1 并希望在 character1 和 character2 上运行动画,您可以使用:

for node in touchedNodes {
    if node.name == "character1" {
      let char1 = node as! SKSpriteNode
      char1.run(animationAction)
      let char2 = childNode(withName: "//character2") as? SKSpriteNode
      char2.run(animationAction)
    } //else if node.name ==....


}

推荐阅读