基本上我需要在我的SpriteKit项目中创建一个UIScrollView但是我在添加SKButtons(用于按钮管理的自定义SKNode类)时遇到了很多问题。所以我开始创建一个带有触摸手势的可滚动SKNode,但很显然,这个栏没有原生的UIScrollView加速:我正在寻找的功能。
因此尝试通过添加本机UIScrollView来赶上这个问题,并抓住每个位置的变化,如下所示:
使用此代码:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[blueNode setPosition:CGPointMake(blueNode.position.x, scrollerUI.contentOffset)];
}
这样做是正确但愚蠢的我忘了如果我添加按钮,触摸手势就不会识别按钮的触摸事件! (UIScrollView具有优先权)。
也许只是一个愚蠢的问题,但我真的不知道如何解决这个问题。也许编写我自己的加速方法?
答案 0 :(得分:2)
一种可能的解决方案是向场景添加点击手势:
override func didMoveToView(view: SKView) {
let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapped:"))
view.addGestureRecognizer(tap)
}
func tapped(tap : UITapGestureRecognizer) {
let viewLocation = tap.locationInView(tap.view)
let location = convertPointFromView(viewLocation)
let node = nodeAtPoint(location)
if node.name == "lvlButton" {
var button = node as! SKButton
button.touchBegan(location)
}
}
答案 1 :(得分:2)
我想我想出了一个处理触摸的解决方案。由于UIScrollView
吃了所有触摸以允许它滚动,因此需要将它们传递给SKScene
。你可以通过继承UIScrollView
:
class SpriteScrollView: UIScrollView {
var scene: SKScene?
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
scene?.touchesBegan(touches, withEvent: event)
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
scene?.touchesMoved(touches, withEvent: event)
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
scene?.touchesCancelled(touches, withEvent: event)
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
scene?.touchesEnded(touches, withEvent: event)
}
}
然后您的场景需要查看触摸是否触及任何节点并适当地将触摸发送到这些节点。因此,在SKScene
添加此内容:
var nodesTouched: [AnyObject] = []
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let location = (touches.first as! UITouch).locationInNode(self)
nodesTouched = nodesAtPoint(location)
for node in nodesTouched as! [SKNode] {
node.touchesBegan(touches, withEvent: event)
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
for node in nodesTouched as! [SKNode] {
node.touchesMoved(touches, withEvent: event)
}
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
for node in nodesTouched as! [SKNode] {
node.touchesCancelled(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
for node in nodesTouched as! [SKNode] {
node.touchesEnded(touches, withEvent: event)
}
}
请注意,这是针对单次触摸并且不能很好地处理错误,如果要正确执行此操作,则需要在if语句中包含一些强制转换
我希望这可以帮助某人,即使问题是几个月之久。