簡體   English   中英

如何在Swift Spritekit中向節點添加觸摸並保持手勢?

[英]How do I add a touch and hold gesture to my node in Swift Spritekit?

我有一個游戲,其中我的節點位於屏幕中間,如果我按住屏幕的左側部分,則該節點將向左移動,如果我按住屏幕的右側,則該節點將向右移動。 我嘗試了一切,但似乎無法正常工作。 謝謝! (我有一些代碼,但是它沒有按照我想要的去做。如果您想看到它以及它的不良之處,請提出來。)

編輯代碼:

    var location = touch.locationInNode(self)

    if location.x < self.size.width/2 {
        // left code
        let moveTOLeft = SKAction.moveByX(-300, y: 0, duration: 0.6)
        hero.runAction(moveTOLeft)
    }
    else {
        // right code
        let moveTORight = SKAction.moveByX(300, y: 0, duration: 0.6)
        hero.runAction(moveTORight)


    }

您必須檢查每次更新中觸摸的位置,以確定角色移動的方向。

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch = touches.first as! UITouch
    var point = touch.locationInView(self)
    touchXPosition = point.x
    touchingScreen = true
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    touchingScreen = false
}

override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        if touchXPosition > CGRectGetMidX(self.frame) {
            // move character to the right.
        }
        else {
            // move character to the left. 
        }
    }
    else { // if no touches.
        // move character back to middle of screen. Or just do nothing.
    }
}

暫無
暫無

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

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