SpriteKit GameScene函数在被按钮调用后不会添加SKSpriteNode [英] SpriteKit GameScene function won't add SKSpriteNode after being called by button

查看:110
本文介绍了SpriteKit GameScene函数在被按钮调用后不会添加SKSpriteNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了fireLaser()函数是否可以调用并可以打印到控制台,但是激光从未添加到场景中.如果我将代码复制并粘贴到fireLaser()函数中,它将在didMoveToView()函数中起作用.

I checked that the fireLaser() function is called as it can be accessed and print out to console but the laser is never added to the scene. If I copy and paste the code in the fireLaser() function it works in the didMoveToView() function.

let character = SKSpriteNode(imageNamed: "monkey")
let laser = SKSpriteNode(imageNamed: "bullet_yellow")

override func didMoveToView(view: SKView) {
    var background : SKSpriteNode = SKSpriteNode (imageNamed: "space.png")
    background.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
    background.size = self.frame.size
    self.addChild(background)
    character.position = CGPoint(x: size.width * 0.5, y: size.height * 0.25)
    addChild(character)

//Shoots Laser From Character
func fireLaser(){
    laser.position = character.position
    addChild(laser)
    let laserDestination = CGPoint(x: character.position.x, y: self.size.height)
    let actionMove = SKAction.moveTo(laserDestination, duration: 2.0)
    let actionMoveDone = SKAction.removeFromParent()
    laser.runAction(SKAction.sequence([actionMove, actionMoveDone]))
    println ("check")
}

//从游戏视图控制器

@IBAction func firePressed(){
    GameScene().fireLaser()
}

推荐答案

此部分:

@IBAction func firePressed(){
    GameScene().fireLaser()
}

...您是要实例化一个新的GameScene并立即调用它吗?可能没有先在SKView中展示场景吗?

... do you mean to instantiate a new GameScene and call fireLaser() on it right away? Without probably presenting the scene in the SKView first?

我认为正在发生的事情是,每当按下按钮时,您就会运行firePressed()方法,该方法将创建GameScene对象的新实例(GameScene()部分),在该实例上运行fireLaser()方法,然后完成它.问题是,这是另一个游戏场景,即不是您的SKView中的游戏场景.

What I think is happening is that whenever a button is pressed you run firePressed() method, which would create a new instance of GameScene object (GameScene() part), run fireLaser() method on that instance, and then be done with it. Problem is, it is another game scene, that is, not the one you have in your SKView.

相反,您应该在已经 的场景上运行fireLaser().

Instead you should run fireLaser() on the scene that is already there.

例如像这样:

@IBAction func firePressed(){
    skView.scene?.fireLaser()
}

这篇关于SpriteKit GameScene函数在被按钮调用后不会添加SKSpriteNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆