maxgribov / Spine

Unofficial Spine runtime Swift library, allows you to play animations created in the Spine app (http://esotericsoftware.com).
MIT License
188 stars 36 forks source link

[HELP] - Random Skin Attachments #35

Closed gholias closed 1 year ago

gholias commented 4 years ago

I have 3 skins in my model. I'm looking for a way to randomize the bones by combining the skins.

For example, let's say I have 3 bones: head, body, and legs I would like to have the image for head to come from skin1, the body from skin2, and the legs from skin3. Is this possible?

gholias commented 4 years ago

I found a way to do by manipulating the model json string before creating the skeleton. It is not pretty, but works and Im going to leave the solution here in case someone else need that

` func randomZombie() throws {

    if character != nil && character.parent != nil {
        character.removeFromParent()
    }

    // loading spine model json from bundle
    if let filepath = Bundle.main.path(forResource: "zombie", ofType: "json") {
        do {
            var contents = try String(contentsOfFile: filepath)

            // getting a random skin number. I have 3 skins defined in spine
            let r = Int.random(in: 1...3)
            // replacing the image reference to the skins to a random skin image
            contents = contents.replacingOccurrences(of: "zombie1/Face 01", with: "zombie\(r)/Face 01")
            contents = contents.replacingOccurrences(of: "zombie1/Head", with: "zombie\(r)/Head")
            let json = Data(contents.utf8)
            let model = try JSONDecoder().decode(SpineModel.self, from: json)

            character = Skeleton(model, atlas: "Zombie")

            character.applySkin(named: "zombie1")

            self.addChild(character)

        } catch {
           throw error
        }
    } else {
        fatalError()
    }

}`
maxgribov commented 1 year ago

working on convenience api for this in v3 branch