sprite-kit - 以编程方式构建的节点上的 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)
}
我不想像现在那样立即运行动作——我希望能够通过开始触摸来启动和停止动作。
我之前为每个角色编写了一个动画方法,但我试图简化整个事情——对任何想法都开放!
谢谢
解决方案
您可以使用以下代码在您的触摸位置获取节点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 ==....
}
推荐阅读
- c# - c# 将 io 流转换为 byte[] 很慢
- java - Whenever i edit in java file , i have to restart apache server for apply those changes in class file
- angular - Error: Schema validation failed with the following errors: Data path "" should NOT have additional properties(project)
- drake - 为 MultibodyTree 中的模型实例计算广义惯性矩阵的简单方法?
- java - 如何将 CellValueFactory 设置为 javafx 中各种属性的函数?
- xcode - Visual Studio 不会编译 Xamarin IOS 找不到 SDK bin 目录
- ios - "error":"Bad Request","message":"必需的 int 参数 'customerId' 不存在",
- mysql - 在 MySQL 查询中的一系列联合选择后无法创建总计行
- python - 不支持的 BMP 压缩 - BMP 到 JPEG - PIL - Python
- java - 使用replace()在java中用不同的字符串替换字符串的3个相同字符