SpriteKit GameScene function won't add SKSpriteNode after being called by button

僤鯓⒐⒋嵵緔 提交于 2019-12-25 06:02:10

问题


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")
}

//FROM GAME VIEW CONTROLLER

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

回答1:


This part:

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

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

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.

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

E.g. something like:

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


来源:https://stackoverflow.com/questions/31362049/spritekit-gamescene-function-wont-add-skspritenode-after-being-called-by-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!