gpt4 book ai didi

swift - 在 SpriteKit 游戏中使用初始值设定项在 Swift 中创建 Sprite 节点

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:21 24 4
gpt4 key购买 nike

我们创建加载到场景中的 Sprite 节点的方式如下:

var createNode: SKNode!

In viewDidLoad:
createNode = createNode1
addChild(createNode)

然后沿着这条线我们有一个创建这个节点的方法,例如:

func createNode1 () -> SKNode {
// load and create node here
{

假设我们使用 init() 方法或初始化器创建了相同的节点,而不是我们在方法 createNode1 中所做的。这会有什么不同。我使用的目的是在我的整个应用程序中使用同一个节点。

最佳答案

我也可以帮你解决这个问题。

主要区别在于,如果您只是创建函数

 createNode1(...) -> SKNode {....

您所能做的就是该方法中的内容,例如创建节点。

  let node1 = createNode1()
addChild(node1)

另一方面,如果您要使用子类,则可以创建特定于该节点的方法/属性,您可以在创建节点的场景中轻松调用这些方法/属性。

例如

 class Node: SKSpriteNode {

var testBool = false

init(....) {
// node set up code

}


func test1() {
// some code relevant to the node
}

func test2() {
// some code relevant to the node
}
}

现在在您创建节点的 gameScene 中,您可以调用这些方法或属性

 class GameScene: SKScene {

var node1: Node!
var node2: Node!

didMoveToView........ {

node1 = Node(...)
addChild(node1)

node2 = Node(...)
addChild(node2)

node1.test1()
node1.test2()
node1.testBool = true

// you notice that I am only calling the methods for node 1, which means that node2 test func are not called yet and testBool is still false.

// see the flexibility in this?
// Main uses for this could be methods/properties for things such as animations, health, etc
}

如果您没有子类化,那么这些方法/属性就必须在您的 GameScene 中的某个地方,而它们可能实际上不应该在某个地方,因为它们特定于该节点而不是场景。您也不能添加多个节点,只能使用 node1 或 node2 等实例来访问特定节点的方法/属性。

所以总而言之,如果您只需要渲染节点而不需要其他任何东西,那么您可以只保留该功能。

但是,如果您有与该角色相关的特定方法(我相信您有),那么您应该创建子类,因为它使您的代码的意图更清晰,总体上更简洁。

这是否回答了您的问题?

关于swift - 在 SpriteKit 游戏中使用初始值设定项在 Swift 中创建 Sprite 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com