如何从代码中访问实体 - 游戏套件
问题描述:
我有我在场景中添加一个节点。同样在现场,我给它一个反弹组件。该组件如下所示:如何从代码中访问实体 - 游戏套件
class BounceComponent: GKComponent, ComponentSetupProt {
var bounce: SKAction?
var node: SKSpriteNode?
@GKInspectable var diff: CGFloat = 0.2
@GKInspectable var startScale: CGFloat = 1
@GKInspectable var duration: TimeInterval = 0.5
override init() {
super.init()
comps.append(self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup() {
print("setup")
node = entity?.component(ofType: GKSKNodeComponent.self)!.node as? SKSpriteNode
setupBounce()
}
func setupBounce() {
...
}
func performBounce() {
print("performing")
node?.run(bounce!)
}
}//
在我的场景文件的didMove函数中,它调用组件setup()。这工作正常。我试图调用函数performBounce()当我按一下按钮...
if (play?.contains(pos))! {
print("test")
if let _ = play?.entity {
print("we have an entity")
}
play?.entity?.component(ofType: BounceComponent.self)?.performBounce()
}
当我点击,它打印的唯一的事情是“测试”和实体是零。我的假设是,当你添加一个节点到编辑器,它也设置了该节点的实体下,所以我不知道为什么它是零。好奇,如果任何人都可以阐明这一点?
感谢您的帮助!
答
在SKSpriteNode的实体是一个弱引用,你需要确保你从你的gameplaykit对象
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Load 'GameScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
if let scene = GKScene(fileNamed: "Main") {
// Get the SKScene from the loaded GKScene
if let sceneNode = scene.rootNode as? Main {
sceneNode.entities = scene.entities // add this
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFill
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.showsDrawCount = true
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
}
class Main: Base {
var entities = [GKEntity]() // add this
+0
,所以这是很重要......我删除的思维,我并不需要它。 – Discoveringmypath
什么是玩保留您的实体?你是否添加了任何组件来玩? – Knight0fDragon
玩的是按钮,我在场景编辑器中添加的,我在编辑器中添加的组件。这个if语句在我的着落函数中。没有子类的按钮,播放只是我对按钮的引用存储在现场 – Discoveringmypath
一个变量,这个在你送我前面的代码?我需要看到更多的,因为它可以变得有点棘手 – Knight0fDragon