'Animating a sprite with SpriteView under iOS15
Trying to animate a sprite node within SpriteKit using SwiftUI but not having much success.
Created a touchable sprite, that works. But tried a texture map, does nothing. Tried manually changing the textures, does nothing.
import SwiftUI
import SpriteKit
class GameScene: SKScene {
private var cat1: Cat!
private var cat2: Cat!
private var catAnimation: SKAction!
func createCats() {
var textures:[SKTexture] = []
for i in 1...4 {
textures.append(SKTexture(imageNamed: "img\(i)"))
}
print("tex \(textures.count)")
catAnimation = SKAction.animate(withNormalTextures: textures, timePerFrame: 1)
cat1 = Cat(texture: textures.first, color: UIColor.red, size: CGSize(width: 48, height: 48))
cat1.position = CGPoint(x: 64, y: 128)
cat1.color = .magenta
cat1.isUserInteractionEnabled = true
cat1.delegate = self
addChild(cat1)
cat2 = Cat(texture: textures.first, color: UIColor.red, size: CGSize(width: 48, height: 48))
cat2.position = CGPoint(x: 128, y: 128)
cat2.color = .green
cat2.isUserInteractionEnabled = true
cat2.delegate = self
addChild(cat2)
}
override func didMove(to view: SKView) {
createCats()
}
}
extension GameScene: CatDelegate {
func catTouched(cat: Cat) {
print("cat of color \(cat.color)")
cat.run(SKAction.repeat(catAnimation, count: 4))
}
}
protocol CatDelegate {
func catTouched(cat: Cat)
}
class Cat: SKSpriteNode {
var delegate: CatDelegate!
var isEnabled = true
var sendTouchesToScene = true
var colour: SKColor = .blue
var textures:[SKTexture] = []
var count = 0
override init(texture: SKTexture!, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
for i in 1...4 {
textures.append(SKTexture(imageNamed: "img\(i)"))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent!) {
guard isEnabled else { return }
//send touch to scene if you need to handle further touches by the scene
if sendTouchesToScene {
super.touchesBegan(touches, with: event)
}
self.colorBlendFactor = 1.0
//handle touches for cat
delegate?.catTouched(cat: self)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
//
}
}
struct ContentView: View {
var scene: SKScene {
let scene = GameScene()
scene.size = CGSize(width: 256, height: 256)
scene.scaleMode = .fill
scene.backgroundColor = .white
return scene
}
var body: some View {
SpriteView(scene: scene)
.frame(width: 256, height: 256)
.border(Color.red)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
let duration = UInt64(seconds * 1000_000_000)
try await sleep(nanoseconds: duration)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
