我在游戏上有一个标题画面,我试图学习制作并希望添加一个响应用户摇晃的功能。该功能在独立但不在此页面时有效。不工作我的意思似乎什么都不做(甚至不打印到日志)。
有问题的功能是motionEnded func。
import SpriteKit
import AVFoundation
import iAd
class GameScene: SKScene {
//loud soundfiles
var titleMusic = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Loping Sting", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
let playButton = SKSpriteNode(imageNamed: "PlayNow")
let titleScreen = SKSpriteNode(imageNamed: "Title")
let titleOrange = SKSpriteNode(imageNamed: "hero")
override func didMoveToView(view: SKView) {
//stop music from game
musicPlayer.stop()
//play sound file
audioPlayer = AVAudioPlayer(contentsOfURL: titleMusic, error: nil)
audioPlayer.prepareToPlay()
audioPlayer.play()
self.titleScreen.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 100)
self.addChild(self.titleScreen)
self.addChild(self.playButton)
//animate button
let pulseUp = SKAction.scaleTo(1.1, duration: 0.9)
let pulseDown = SKAction.scaleTo(0.7, duration: 0.9)
let pulse = SKAction.sequence([pulseDown, pulseUp])
let repeatPulse = SKAction.repeatActionForever(pulse)
self.playButton.runAction(repeatPulse)
//show hero
titleOrange.position = CGPointMake(CGRectGetMidX(self.frame), 363)
self.addChild(titleOrange)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.playButton {
var scene = PlayScene(size: self.size)
let skView = self.view as SKView?
scene.scaleMode = .ResizeFill
scene.size = skView!.bounds.size
skView?.presentScene(scene)
}
}
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
if motion == .MotionShake {
println("Shake")
}
}
override func update(currentTime: CFTimeInterval) {
}
}
答案 0 :(得分:1)
由于您之前有过工作,我认为您已将applicationSupportsShakeToEdit
设置为true
(无论如何这是默认设置)。
然后你需要确保你的场景GameScene
成为第一个响应者 - 第一个响应者(顾名思义)将是第一个有机会回应运动事件的人,之后它会进展向上responder chain。 SKScene
符合UIResponder
协议,因此您只需要通过覆盖方法让它成为第一响应者,然后在场景出现/消失时调用几个响应方法:
override func canBecomeFirstResponder() -> Bool {
return true
}
override func didMoveToView(view: SKView) {
// ...
becomeFirstResponder()
}
override func willMoveFromView(view: SKView) {
// ...
resignFirstResponder()
}
请注意,根据您应用的结构,让您的场景成为第一个响应者可能会影响应用中其他位置的其他事件处理代码。