【问题标题】:how to code UIbuttons/IBactions in touches methods for a Sprite kit game如何在 Sprite 工具包游戏的触摸方法中编写 UIbuttons/IBactions
【发布时间】:2016-03-22 20:00:30
【问题描述】:

在我之前的应用程序(单视图应用程序)中,我在 IBActions 中使用 touch down 和 touch up 来获取游戏中的按钮。但是在 SpriteKit 游戏中,您必须完全创建场景,而且我很难编写 touchesBegan 方法。

这是我的基本运动方法/功能:

func heroMovementLeft () {

    hero.position = CGPointMake(hero.position.x - 0.5,hero.position.y);

}

这是我的左箭头节点,我希望在触摸左箭头时调用 HeroMovementLeft 方法

func LeftArrow () {

    let LeftArrow = SKSpriteNode(imageNamed: "Left Arrow.png")
    LeftArrow.position = CGPointMake(30, 30)
    self.addChild(LeftArrow)
} 

这里是我现在编写touchesBegan 方法的地方

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

        for touch in touches {
        }
}

我要创建一个 if 语句吗?我是否让 touch 成为变量?我需要在我的 touches started 方法中写什么,以便我的英雄在左箭头被触摸时会移动。我在网上查遍了,找不到这个问题的答案,请帮忙。

【问题讨论】:

  • 有几条路可以走。最简单的方法是为要移动的节点命名,并在 touchesBegan 方法中使用nodeAtPoint 查看“如果您正在触摸正确的节点”...

标签: ios swift cocoa-touch sprite-kit touchesbegan


【解决方案1】:

您基本上有 2 个选项来识别您的精灵

1) 将它们设为场景的全局属性

   class YourScene: SKScene {

    var leftArrow: SKSpriteNode!

    override func didMoveToView(view: SKView) {

    }


    func leftArrow() {

        leftArrow = SKSpriteNode(imageNamed: "Left Arrow.png")
        leftArrow.position = CGPointMake(30, 30)
        addChild(leftArrow)
   }
 }

比触摸开始你可以得到这样的位置

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

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

         if node == leftArrow {
             heroMovementLeft()
         }
      }
   }

选项 2 是给你的精灵命名

 func leftArrow() {
    let leftArrow = SKSpriteNode(...)
    leftArrow.name = "LeftArrow"
    ...
 }

然后在 touches started 方法中检查这些名称

  ....
  if node.name == "LeftArrow" {
     heroMovementLeft()
  }

作为旁注,您应该以小写字母开头属性或 func,并且仅以大写字母开头类、结构和协议。

【讨论】:

  • 感谢您的帮助@crachoveride777 我不再收到任何错误通知,但是当我在模拟器中运行应用程序时,屏幕上没有显示箭头。我尝试了多个不同的 CGpoints。这可能是因为我没有在我的覆盖函数中执行 addChild(leftArrow) 代码 didMoveToView(view: SKView) } ???
  • 您总是需要调用 addChild(YourSprite) 将其添加到场景中。
  • 我不认为这与您提出的问题无关。您是否有其他图像,例如可能覆盖它的背景精灵。如果你有的话,试着给箭头一个比你的背景精灵更高的 zPosition。
  • func LeftArrow() { leftArrow = SKSpriteNode(imageNamed: "LeftArrow.png") leftArrow.position = CGPointMake(30, 30) addChild(leftArrow) leftArrow.xScale = 300 eftArrow.yScale = 300 }覆盖 func touchesBegan(touches: Set, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(self) let node = nodeAtPoint(location) if node == leftArrow { heroMovementLeft() 我什至更改了 CGpoints 并增加了图像的大小,以防精灵正在加载但它仍然没有加载到屏幕上
  • 你在哪里调用 func LeftArrow() ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多