SKSpriteNode drag movement by touch

若如初见. 提交于 2019-12-22 12:39:30

问题


I'm trying to drag a SKSpirteNode around the screen by touching the screen. But I want to be able to do a constant movement of the Sprite, currently my code only moves the sprite to the location of my touch but if I hold and move the sprite will not follow. Moreover I don't want to "have" to touch the SKSpriteNode to activate the movement, I want to touch anywhere on the screen and to have a movement response from that SKSpriteNode.

Here is my current code:

class GameScene: SKScene {
   override func didMoveToView(view: SKView) {
    // SpriteNode I want to drag around
    basket = SKSpriteNode(texture: basketTexture)
    self.addChild(basket)
   }

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    var nodeTouched = SKNode()
    var currentNodeTouched = SKNode()

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

        nodeTouched = self.nodeAtPoint(location)
        basket.position = location

    }

Thank you any help appreciated.


回答1:


I solved this by using the func touchesMoved instead of touchesBegan and works perfectly and smoothly. here is the final code:

class GameScene: SKScene {
 override func didMoveToView(view: SKView) {
// SpriteNode I want to drag around
basket = SKSpriteNode(texture: basketTexture)
self.addChild(basket)
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */

var nodeTouched = SKNode()
var currentNodeTouched = SKNode()

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

    nodeTouched = self.nodeAtPoint(location)
    basket.position = location

}


来源:https://stackoverflow.com/questions/26207691/skspritenode-drag-movement-by-touch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!