簡體   English   中英

Sprite-kit:檢測左右觸摸

[英]Sprite-kit: detecting left & right touches

在新的游戲中,我試圖建立,我想知道,當用戶觸摸屏幕的右側左側做一些邏輯。

我的代碼:

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

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        var isRight : Bool = false
        var isLeft : Bool = false

        if(location.x < self.size.width/2){
            isLeft = true
            println("Left")
        }

        if(location.x > self.size.width/2){
            //
            isRight = true
            println("Right")
        }
        if (isRight && isLeft){
            println("Both touched")
            // do something..
        }
    }
}

安慰:

Right
Left

我的代碼似乎無效。 我在這里做錯了什么? 有人有更好的解決方案嗎?

做這個;

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

   var isRight : Bool = false
   var isLeft : Bool = false

   for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        if(location.x < self.size.width/2){
            isLeft = true
            println("Left")
        }

        if(location.x > self.size.width/2){
            //
            isRight = true
            println("Right")
        }
    }

   if (isRight && isLeft){
      println("Both touched")
      // do something..
   }

}

更新:Swift 2.2

對於SKView:

class skView:SKView {

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

        var isRight : Bool = false
        var isLeft : Bool = false

        for touch in touches {
            let location = touch.locationInView(self);

            if(location.x < self.frame.size.width/2){
                isLeft = true
                print("Left")
            }

            if(location.x > self.frame.size.width/2){
                //
                isRight = true
                print("Right")
            }
        }

        if (isRight && isLeft){
            print("Both touched")
            // do something..
        }

    }
}

對於SKNode:

class skNode: SKNode {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        var isRight : Bool = false
        var isLeft : Bool = false

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

            if(location.x < self.frame.size.width/2){
                isLeft = true
                print("Left")
            }

            if(location.x > self.frame.size.width/2){
                //
                isRight = true
                print("Right")
            }
        }

        if (isRight && isLeft){
            print("Both touched")
            // do something..
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM