下面,我有一个 SKSpriteNode 图像,我还使用纹理图集 (Texture Atlas) 和 SKAction.animate 来通过我的一个纹理数组进行动画处理。当我第一次运行该应用程序时,图像直接显示在屏幕中央,并按应有的方式进行动画处理。但是当我尝试通过 CGPoint 定位节点时,它没有移动。我什至尝试过“CGPoint(x: 0, y: -self.height/2)”,因为我希望图像显示在屏幕的最底部中心,但没有工作。有时,当我在 iPhone 上运行该应用程序时,图像有时甚至不存在,我必须重新运行该应用程序。我一定做错了什么,但我的代码似乎是正确的?
class GameScene: SKScene {
let background = SKSpriteNode(texture:SKTexture(imageNamed: "background"))
var person = SKSpriteNode()
let atlas = SKTextureAtlas(named: "people")
var textureArray = [SKTexture]()
override func didMove(to view: SKView) {
background.position = CGPoint(x: 0, y: 0)
self.background.zPosition = 0.0
self.addChild(background)
person = SKSpriteNode(imageNamed: "person1.png")
person.position = CGPoint(x: self.frame.size.width, y: self.frame.size.height/2)
self.person.zPosition = 1.0
person.size = CGSize(width: 150, height: 129)
person = SKSpriteNode(imageNamed: atlas.textureNames[0])
for i in 1...atlas.textureNames.count {
let Name = "person\(i).png"
textureArray.append(SKTexture(imageNamed: Name))
}
let myAnimation = SKAction.animate(with: textureArray, timePerFrame: 0.1)
self.addChild(person)
person.run(SKAction.repeatForever(myAnimation))
}
override func update(_ currentTime: TimeInterval) {
}
}
最佳答案
我还没有测试过这个,但我怀疑我知道问题可能出在哪里。
这三行位于代码的不同位置:
var person = SKSpriteNode()
person = SKSpriteNode(imageNamed: “person1.png")
person = SKSpriteNode(imageNamed: atlas.textureNames[0])
所有这些行创建一个新 SKSpriteNode 并分配对该新 Sprite 节点的引用,该引用由名为 person
的变量保存。
在代码中,您更改了第二个 person
节点的位置。然后创建第三个 person
节点。这意味着您之前设置的位置不会对第三个 person
节点产生任何影响,因为只更改了第二个 person
位置。
我建议仅创建一个 person
节点,然后设置其位置、zposition、大小等。要解决此问题,请考虑替换 var person = SKSpriteNode()
与 var person: SKSpriteNode?
。然后还将行 person = SKSpriteNode(imageNamed: “person1.png")
替换为 person = SKSpriteNode(imageNamed: atlas.textureNames[0])
,当然还要删除person = SKSpriteNode(imageNamed: atlas.textureNames[0])
行发生在 for
循环之前。
由于 person
现在被定义为可选,因此现在需要以 person?
或在某些情况下以 person!
的形式访问它你确信它不能为零。 Xcode 将显示您需要在何处添加额外的 ?
。
希望这有帮助!
关于swift - 在 Swift 4 中设置 SKSpriteNode 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46267059/