【发布时间】:2015-12-16 14:27:27
【问题描述】:
我正在学习 swift(和 spritekit)并尝试制作一个简单的游戏。
在我的游戏中,英雄应该跳跃或躲避......
点击屏幕时英雄需要跳跃,长按屏幕时需要躲避(long gesture)
那么基本的伪代码:
if tapped
heroJump()
else if tappedAndHeld
heroDuck()
我有一个func,几乎在所有教程中都可以看到它处理触摸事件:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self) //need location of tap for something
switch gameState {
case .Play:
//do in game stuff
break
case .GameOver:
//opps game ended
}
break
}
}
super.touchesBegan(touches, withEvent: event)
}
有没有办法在这个触摸事件中包含它来决定它是被点击还是被按住?我似乎无法理解这样一个事实,程序总是会在长手势之前识别轻按?!?
无论如何,为了解决我的问题,我发现了THIS 问题,它向我介绍了识别器,我尝试实施:
override func didMoveToView(view: SKView) {
// other stuff
//add long press gesture, set to start after 0.2 seconds
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
longPressRecognizer.minimumPressDuration = 0.2
self.view!.addGestureRecognizer(longPressRecognizer)
//add tap gesture
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
self.view!.addGestureRecognizer(tapGestureRecognizer)
}
这些是手势调用的函数:
func longPressed(sender: UILongPressGestureRecognizer)
{
if (sender.state == UIGestureRecognizerState.Ended) {
print("no longer pressing...")
} else if (sender.state == UIGestureRecognizerState.Began) {
print("started pressing")
// heroDuck()
}
}
func tapped(sender: UITapGestureRecognizer)
{
print("tapped")
// heroJump()
}
如何将这两件事结合起来? 我可以添加一种方法来确定它是在我的 touchBegins 事件中被点击还是按住,或者我可以放弃该方法并仅使用上述两个函数吗?
如果使用后者,获取位置的诸多问题之一?
或者也许我完全看错了,在 swift/spritekit 中有一个简单和/或内置的方法?
谢谢。
【问题讨论】:
标签: swift cocoa-touch sprite-kit uigesturerecognizer