使用 Swift 创建 SKSpriteNode class 4

Creating an SKSpriteNode class with Swift 4

我已经使用 Swift 4 和 XCode 编写了一个简单的游戏,并且我已经编写了 GameScene 中的所有内容。我所有的元素(怪物、玩家、射弹等)都在 GameScene 中编码。

我想将我的代码转移到专用的 classes(Class 玩家,class 怪物等)

我想知道 SKSpriteNode 的基本结构 class 以及它在 GameScene 中的调用 class ,以便更有效地调整我的代码。

这是我尝试过的示例:

class Vaisseau: SKSpriteNode /*: Creatures */{

var coeur: Int = 0

init(texture: SKTexture, size: CGSize)
{
    let texture = SKTexture(imageNamed: "player")
    super.init(texture: texture, color: UIColor.clear, size: texture.size())
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

GameScene中的初始化:

 let player = Vaisseau()

这是它在 GameScene 中的实际定义方式:

let player = SKSpriteNode(imageNamed: "player")

您正在声明您的 init 有两个参数 (texture: SKTexture, size: CGSize) 但您没有在初始化调用中传递参数

let player = Vaisseau()

您需要将初始化更改为...

let texture = SKTexture(imageNamed: "player")
let player = Vaisseau(texture: texture, size: texture.size())

并将 init 更改为

init(texture: SKTexture, size: CGSize) {
    super.init(texture: texture, color: UIColor.clear, size: size)
}

OR change the init in the class to...

init() {
    let texture = SKTexture(imageNamed: "player")
    super.init(texture: texture, color: UIColor.clear, size: texture.size())
}

并将您的初始化调用保留为...

let player = Vaisseau()
player.position = CGPoint(x: 500, y: 500)
addChild(player)

EDIT added the above 2 lines to show you that those need to be in the scene but other items such as alpha, zPosition, actions, zRotation etc. can be inside of the class

你需要问自己弄清楚要使用哪个 "will the texture for the player ever be different?" 如果是这样,你可能需要考虑传入纹理的第一个选项。