Search code examples
classtextures

Class textures change, but do not show up


In my program I am making, I ma trying to have two different kinds of pieces with different textures, that are of the same class.

As this class is a sub class, I have to set the texture to a default texture in the super.init. I do change the texture, but only the default texture shows up when the program is run.

I have tried to print off the texture, and it says the texture has been changed. What is going on?

Note: I am using checker pieces as stand in pieces. The red checker piece is the stand in one (and the one for the red team). The image should display a black checker piece

Here is the problem:

enter image description here

Here is the print out.

enter image description here

Here is the code for the spawning and for the Rifleman Class:

func spawnBlueRiflemen(at: CGPoint) {
        let newBlueRifle = rifleman()
        newBlueRifle.texture = textureBlueRifle
        newBlueRifle.position = at
        newBlueRifle.team = "Blue"
        print("\(newBlueRifle.texture)")
        self.addChild(newBlueRifle)
    }

class rifleman: Character, pTargetable{
    var health = 10
    init() {
        super.init(tag: 0, team: "generic", currentAction: 0, texture: textureRedRifle)
        var xSize = texture.size().width            // Create The texture for the top ( visible sprite )
        var ySize = texture.size().height
        var size = CGSize(width: xSize, height: ySize)
        self.physicsBody = SKPhysicsBody(texture: texture, size: size)
        self.physicsBody?.isDynamic = false
        self.physicsBody?.affectedByGravity = false            // ( physical body stuff )
        self.physicsBody?.mass = 1.0
        self.name = "\(tag)"
        var top = SKSpriteNode(texture: texture, size: size)
        top.zPosition = layers.characters
        top.color = SKColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        top.colorBlendFactor = 1.0
        self.addChild(top)
    }

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

    func takeDamage(damage: Int) {
        health -= damage
        print("\(tag) lost \(damage) hit points")

        if health <= 0 {
            die()
            print("\(tag) is dead now")
        }
    }

}

Solution

  • You have to initialize "texture" inside the subclass "riflemen" to make the texture changeable.

    E.g.

    ....

    class rifleman: Character, pTargetable{
        var health = 10
        init(texture: SKTexture) {
            super.init(tag: 0, team: "generic", currentAction: 0, texture: texture)
    

    ....