我使用 Swift 4 和 XCode 编写了一个简单的游戏,并且在 GameScene 中编写了所有内容。我的所有元素(怪物、玩家、射弹等)都在 GameScene 中进行编码。
我想将我的代码转移到专用类(玩家类、怪物类等)
我想知道 SKSpriteNode 类的基本结构以及 GameScene 中该类的调用,以便更有效地调整我的代码。
这是我尝试过的示例:
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 有两个参数(纹理:SKTexture,大小: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
要确定使用哪一个,您需要问自己的是“玩家的纹理会有所不同吗?”如果是这样,您可能需要考虑传入纹理的第一个选项。
关于swift - 使用 Swift 4 创建 SKSpriteNode 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244221/