Sprite Node position not updating with touch?

大城市里の小女人 提交于 2019-12-25 01:29:43

问题


Essentially, what I want is for when I touch a node, I want to be able to move it across the screen. The problem is that whenever I move my finger too fast, the node just stops following it.

The spriteNodes in particular that I'm trying to do this with have physics bodies and animating textures so I tried to do the same code with a completely plain spriteNode and I've encountered the same problem.

The code that I have here is pretty simple so I'm not sure if this is a problem with what I've written or if it's just a lag problem that I can't fix. It's also basically the same all throughout touchesBegan, touchesMoved and touchesEnded

for touch in touches {

  let pos = touch.location(in: self)
  let node = self.atPoint(pos)

  if node.name == "activeRedBomb"{
    node.position = pos
  }

  if node.name == "activeBlackBomb"{
    node.position = pos
  }


  if node.name == "test"{
    node.position.x = pos.x
    node.position.y = pos.y
  }


}

回答1:


What's happening is that if you move your finger too fast, then at some point, the touch location will no longer be on the sprite, so you code to move the node won't fire.

What you need to do is set a flag in touchesBegan() to indicate that this sprite is touched, move the sprite to the location of the touch in touchesMoved() if the flag is set and then reset the flag in touchesEnded().

Here's roughly what you need to add for this:

import SpriteKit

class GameScene: SKScene {

var bombIsTouched = false

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        if activeRedBomb.contains(touch.location(in: self)) {
            bombIsTouched = true
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if bombIsTouched {
        activeRedBomb.position = (touches.first?.location(in: self))!
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if bombIsTouched {
        bombIsTouched = false
    }
}    


来源:https://stackoverflow.com/questions/56485910/sprite-node-position-not-updating-with-touch

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