So below, I have one SKSpriteNode image that I'm also animating using Texture Atlas along SKAction.animate to animate through one of my texture arrays. When I first run the app, the image shows up directly in the center of the screen and animates like it should. But when I try to position the node through CGPoint, it doesn't move. I've even tried, "CGPoint(x: 0, y: -self.height / 2)" because I want the image to show up on the very bottom center of the screen but doesn't work. Sometimes when I run the app on my iPhone, the image isn't even there sometimes and I have rerun the application. I must be doing something really wrong but my code seems right?
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) {
}
}
I haven't tested this, but I suspect I know where the problem could be.
You have these three lines in different places of your code:
All these lines create a new SKSpriteNode and assign a reference to that new sprite node to be held by a variable named
person.In your code, you change the position of the 2nd
personnode. Then you create a 3rdpersonnode. This means that the position you set earlier won't have any effect on the 3rdpersonnode, since only the 2ndpersonposition was changed.I would recommend to create only one
personnode, and thereafter set its position, zposition, size, etc. To fix this, consider replacingvar person = SKSpriteNode()withvar person: SKSpriteNode?. Then also replace the lineperson = SKSpriteNode(imageNamed: “person1.png")withperson = SKSpriteNode(imageNamed: atlas.textureNames[0]), and of course remove the lineperson = SKSpriteNode(imageNamed: atlas.textureNames[0])that occurs just before theforloop.Since
personis now defined as an optional, it will now need to be accessed asperson?, or asperson!in cases where you are sure it can't be nil. Xcode will show you where you need to add the extra?.Hope this helps!