Search code examples
swiftsprite-kitskspritenode

Swift 4 SKSpriteNode cast to CustomClass


Hello so what I'm trying to do is create a spriteNode programmatically and assign it a class. So that I can easily manage the nodes characteristics, such as custom level, guns, hp, etc... heres how I'm trying to do that.

let player = SKSpriteNode(imageNamed: "charcter") as? Dummyplayer
    player.physicsBody?.affectedByGravity = false
    player.physicsBody?.allowsRotation = false
    player.size.height = 75
    player.size.width = 75
    addChild(player)
    player.position.x = CGFloat(x)
    player.position.y = CGFloat(y)

but it fails saying it cannot cast type SKSpriteNode to type game.Dummplayer,, the class Dummyplayer is of type SKSpriteNode so I'm not sure what I'm doing wrong.


Solution

  • You are creating a SKSpriteNode and then you are casting it to DummyPlayer. The cast will always fail because player is NOT a DummyPlayer.

    Solution

    Given the Dummyplayer class defined as follow

    class Dummyplayer: SKSpriteNode { }
    

    You need to create a value of type Dummyplayer

    if let player = Dummyplayer(imageNamed: "character") {
        ....
    }