Reputation: 519
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) {
}
}
Upvotes: 2
Views: 2068
Reputation: 990
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:
var person = SKSpriteNode()
person = SKSpriteNode(imageNamed: “person1.png")
person = SKSpriteNode(imageNamed: atlas.textureNames[0])
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 person
node. Then you create a 3rd person
node. This means that the position you set earlier won't have any effect on the 3rd person
node, since only the 2nd person
position was changed.
I would recommend to create only one person
node, and thereafter set its position, zposition, size, etc. To fix this, consider replacing var person = SKSpriteNode()
with var person: SKSpriteNode?
. Then also replace the line person = SKSpriteNode(imageNamed: “person1.png")
with person = SKSpriteNode(imageNamed: atlas.textureNames[0])
, and of course remove the line person = SKSpriteNode(imageNamed: atlas.textureNames[0])
that occurs just before the for
loop.
Since person
is now defined as an optional, it will now need to be accessed as person?
, or as person!
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!
Upvotes: 2