8
votes

I'm making a simple tile-based game in SpriteKit and I'm having some difficulty with high CPU usage in my game. I have a map made of 60 tiles, and each tile is a subclass of SKSpriteNode. Just displaying these 60 sprites in the scene is using up to 80% of CPU in the iPhone 6s simulator. There is no motion, user interaction, or physics going on. When I made the same game in UIKit and not SpriteKit my CPU usage was 0. What could be using so much CPU?

my tile class:

import SpriteKit
import UIKit
class Tile: SKSpriteNode {

var tileType = "grass", tileX = 0, tileY = 0
    init (tileType: String, tileX: Int, tileY: Int) {
        self.tileType = tileType
        self.tileX = tileX
        self.tileY = tileY
        let texture = SKTexture(imageNamed: tileType)
        super.init(texture: texture, color: UIColor(), size: texture.size())
        self.userInteractionEnabled = true
        self.position = CGPoint(x: CGFloat(45+64*(tileX-1)), y: CGFloat(47+56*(tileY-1)))
        self.zPosition = -1

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

and my Sprite Kit scene code:

import SpriteKit
var map: [[String]] = [["grass","water","grass","rocky","rocky","grass","grass","grass","grass","water"],["grass","water","grass","grass","rocky","rocky","grass","grass","water","water"],["grass","water","water","grass","rocky","grass","grass","water","water","water"],["grass","grass","water","rocky","rocky","grass","grass","water","water","water"],["grass","grass","water","rocky","rocky","grass","water","water","water","water"],["grass","grass","water","rocky","rocky","grass","water","water","water","water"] ]
class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        for (rowNumber, row) in map.enumerate() {
            for (columnNumber, type) in row.enumerate() {
                let theTile = Tile(tileType: type, tileX: columnNumber+1, tileY: rowNumber+1)

                self.addChild(theTile)
            }
        }
        self.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0)


    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}
2

2 Answers

12
votes

Iphone Simulator on Xcode have a much greater CPU Usage than in a real device.

Test in a real device to have a real metric about CPU Usage.

1
votes

Tyshka, you need to reuse resources. Your code creates a new SKTexture for the exact same input image data. Just create one SKTexture and then set that as the texture for the new node. Add a map to your code so that the SKTexture can be checked and reused given the texture string name.