Swift 4 SKSpriteNode cast to CustomClass

时间:2018-02-03 11:25:47

标签: swift sprite-kit skspritenode

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.

1 个答案:

答案 0 :(得分:0)

您正在创建SKSpriteNode,然后将其投射到DummyPlayer。演员将永远失败,因为玩家 a DummyPlayer

解决方案

鉴于Dummyplayer类定义如下

class Dummyplayer: SKSpriteNode { }

您需要创建Dummyplayer

类型的值
if let player = Dummyplayer(imageNamed: "character") {
    ....
}
相关问题