我的雪碧不会执行我告诉它的动作?

时间:2016-10-27 18:19:18

标签: swift xcode sprite-kit

我正在使用Swift和SpriteKit在Xcode 7中创建一个应用程序。我的想法是让一个用手指移动的宇宙飞船,或者基本上跟随它,但我遇到了麻烦。这是代码:

import Foundation
import SpriteKit

class secondScene: SKScene {

override func didMoveToView(view: SKView) {

   // var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector(spawnBullets()), userInfo: nil, repeats: true)

    //buttons
    let leftbutton = SKSpriteNode(imageNamed: "LeftArrow")
    leftbutton.position = CGPoint(x: self.frame.size.width*0.2, y: self.frame.size.height*0.1)
    leftbutton.size = CGSize(width: 220, height: 80)
    leftbutton.color = SKColor.blueColor()
    leftbutton.zPosition = 100
    self.addChild(leftbutton)

    let rightbutton = SKSpriteNode(imageNamed: "RightArrow")
    rightbutton.position = CGPoint(x: self.frame.size.width*0.8, y: self.frame.size.height*0.1)
    rightbutton.size = CGSize(width: 220, height: 80)
    rightbutton.color = SKColor.blueColor()
    rightbutton.zPosition = 100
    self.addChild(rightbutton)

    //spaceship
    let spaceship = SKSpriteNode(imageNamed: "spaceship")
    spaceship.zPosition = 100
    spaceship.size = CGSize(width: 200, height: 120)
    spaceship.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height*0.15)
    self.addChild(spaceship)           
}

let spaceship = SKSpriteNode(imageNamed: "spaceship")

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        spaceship.position.x = location.x
    }
}
}

我跑这个对我而言,似乎我的宇宙飞船应该跟着我的手指,但它并没有。它只是停留在我之前指定的位置。我没有错误,我没有想法。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在didMoveToView

中的太空船代码中删除此行
let spaceship = SKSpriteNode(imageNamed: "spaceship")

这样你实际上使用了你在touchesBegan上创建的全局属性。

您可能还想在touchesMoved中包含/移动代码。

 override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

     for touch in touches {
         let location = touch.locationInNode(self)

          spaceship.position.x = location.x
     }  
 }

希望这有帮助