【问题标题】:Not able to select pause button I have added to the screen无法选择我已添加到屏幕的暂停按钮
【发布时间】:2018-05-21 15:12:11
【问题描述】:

我的游戏设置有背景,中间有一条道路,然后顶部有一个显示得分和暂停按钮的栏。道路和背景的zPosition为1。顶部的条zPosition为4,暂停按钮zPosition也是4。

道路和背景代码。

    road.position = CGPoint(x: CGFloat(0), y: CGFloat(0))
    road.zPosition = 1
    road.name = roadName
    background.position = CGPoint(x: CGFloat(0), y: CGFloat(0))
    background.zPosition = 1
    background.name = backgroundName

    addChild(background)
    addChild(road)

顶部栏的代码。

    topBar = SKSpriteNode(color: .black, size: CGSize(width: screenWidth, height: CGFloat(150)))
    topBar.position = CGPoint(x: 0, y: (screenHeight/2) + topBar.size.height/2)
    topBar.zPosition = 4
    topBar.name = topBarName

    addChild(topBar)

暂停按钮的代码。

    pauseButton.position = CGPoint(x: (-topBar.size.width/2) + (pauseButton.size.width + (pauseButton.size.width/2)), y: 0)
    pauseButton.zPosition = 4
    pauseButton.name = pauseButtonName

    topBar.addChild(pauseButton)

在我的touches开始函数中,我试图搜索touch位置的节点,但它只返回道路和背景的名称。它甚至没有拿起 topBar 或暂停按钮。

for node in nodes
            {
                print(node.name)

                if node.name == pauseButtonName
                {
                    print("paused")
                }
            }

这将输出

Optional("Road")
Optional("Background")

我也尝试过这种方法,但从未返回“暂停”。

 if pauseButton.contains(touch.location(in: self))
            {
                print("paused")
            }

我认为注意顶部栏最初位于屏幕之外可能很重要。当你开始游戏时,它会运行一个 SKAction 来移动屏幕上的栏。

topBar.run(SKAction.moveTo(y: (screenHeight/2) - (topBar.size.height/2), duration: 0.5))

为什么我无法选择暂停按钮,如何解决?

【问题讨论】:

标签: swift sprite-kit skspritenode touchesbegan


【解决方案1】:

我通过使用此代码解决了这个问题。我没有在游戏场景中检查位置,而是在 topBar 中检查了它。

if pauseButton.contains(touch.location(in: topBar))
{
    print("paused")
}

【讨论】:

  • 这似乎不对,触摸 topBar 中的任何位置都会导致它通过/暂停
  • @Knight0fDragon 事实并非如此。我已经在我的应用程序上对其进行了测试,并且还在 topBar 中添加了另一个按钮,它也可以正常工作。它检查我触摸屏幕的点是否存在于暂停按钮坐标系中。由于暂停按钮仅位于左上角,因此只有在我按下该位置时才会调用它。
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多