问题描述
我之前为每个角色使用了单独的方法并将它们写入每个场景文件中,但它很混乱而且很大。
所以为了清理代码,我编写了一个 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)
}
我不想像当前那样立即运行操作 - 我希望能够通过开始触摸来启动和停止操作。
我之前为每个角色编写了一个动画方法,但我正在尝试简化整个过程 - 对任何想法持开放态度!
谢谢
解决方法
您可以使用 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 ==....
}