如何在Sprite工具包游戏的触摸方法中编写UIbuttons / IBactions代码

时间:2016-03-22 20:00:31

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

在我之前的应用程序(单视图应用程序)中,我使用了触摸并在IBActions中触摸我的游戏中的按钮。但是在SpriteKit游戏中你必须完全创建场景,我很难用touchesBegan方法编码。

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

func heroMovementLeft () {

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

}

这是我的左箭头节点,我希望在触摸LeftArrow时调用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语句?我是否触摸变量?在触摸开始的方法中我需要写什么才能让我的英雄在触摸左箭头时移动。我已经在网上看了一遍,找不到这个问题的答案,请帮助。

1 个答案:

答案 0 :(得分: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"
    ...
 }

并在触摸开始方法

中检查这些名称
  ....
  if node.name == "LeftArrow" {
     heroMovementLeft()
  }

作为旁注,你应该用小写字母开始你的属性或函数,并且只用大写字母开始类,结构和协议。