Reputation: 25
I am having trouble with my animation in swift. The animation is not playing.
These are my swift files:
This is my sprite file:
import Foundation
import SpriteKit
class Dog: SKSpriteNode {
var dog = SKSpriteNode()
var textureAtlas = SKTextureAtlas()
var textureArray = [SKTexture]()
init() {
super.init(texture: SKTexture(imageNamed:"dog_1"), color: UIColor.clear, size: CGSize(width: 44, height: 25))
textureAtlas = SKTextureAtlas(named: "dog")
for i in 1...textureAtlas.textureNames.count {
let name = "dog_\(i).png"
textureArray.append(SKTexture(imageNamed: name))
}
}
func animate() {
dog.run(SKAction.repeatForever(SKAction.animate(with: textureArray, timePerFrame: 0.1)))
}
func stopAnimation() {
dog.removeAllActions()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
This is my GameScene file:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var dog: Dog!
override func didMove(to view: SKView) {
scene?.backgroundColor = UIColor(red: 132.0/255.0, green: 179.0/255.0, blue: 255.0/255.0, alpha: 1.0)
addDog()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dog.animate()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
dog.stopAnimation()
}
func addDog() {
dog = Dog()
dog.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
addChild(dog)
}
}
I think the problem is in the animate function in the sprite file.
I have tried everything I can think of. Any help would be greatly appreciated.
Upvotes: 1
Views: 251
Reputation: 4526
Within your class Dog you have a var dog that is initialised as an SKSpriteNode. Your start and stop animate functions then operate on that dog, not the class itself and not the other dog in your game scene. As that dog is never added to the scene your animation is never visible.
Remove the dog var and references to it from Dog - the animations should be running on your subclass Dog directly.
Upvotes: 2