如何通过触摸移动图像并按住屏幕的左侧和右侧? - 斯威夫特

时间:2015-12-30 23:53:48

标签: ios swift sprite-kit skspritenode

我需要帮助Swift中的动作。我有SKSpriteNode我需要帮助左右移动触摸和拖动动作以及SKSpriteNode。但只有左右。当我点击另一侧而不是图片的x位置时,只是顺利地跑过来。任何人都可以帮忙怎么做?感谢。

import SpriteKit

class PlayScene: SKScene {

    let rocket = SKSpriteNode(imageNamed: "rocket")

    override func didMoveToView(view: SKView) {
        rocket.position = CGPoint(x: self.frame.width/2, y: self.frame.height * 0.8)
        self.addChild(rocket)
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        rocket.position = CGPoint(x: location.x, y: self.frame.height * 0.8)
    }
}

1 个答案:

答案 0 :(得分:1)

在此,火箭动画1秒到触摸位置,然后如果用户移动手指则随触摸移动。

class GameScene: SKScene {
let rocket = SKSpriteNode(imageNamed: "rocket")
override func didMoveToView(view: SKView) {
    rocket.position = CGPoint(x: self.frame.width/2, y: self.frame.height * 0.8)
    self.addChild(rocket)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        rocket.position = location
    }
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let moveAction = SKAction.moveTo(location, duration: 1/*Or as long as you want it to move*/)
        rocket.runAction(moveAction)
    }
}
}

希望这有帮助。