精灵节点位置不随触摸更新? [英] Sprite Node position not updating with touch?

查看:29
本文介绍了精灵节点位置不随触摸更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本质上,我想要的是当我触摸一个节点时,我希望能够在屏幕上移动它.问题是每当我移动手指太快时,节点就会停止跟随它.

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.

特别是我尝试使用的 spriteNode 具有物理实体和动画纹理,因此我尝试使用完全普通的 spriteNode 执行相同的代码,但我遇到了同样的问题.

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.

我这里的代码非常简单,所以我不确定这是否是我所写的问题,或者只是我无法修复的滞后问题.在整个touchesBegan、touchesMoved和touchesEnded中也基本相同

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
  }


}

推荐答案

发生的情况是,如果你移动手指太快,那么在某些时候,触摸位置将不再在精灵上,所以你编码移动节点不会触发.

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.

你需要做的是在touchesBegan()中设置一个标志来表示这个精灵被触摸了,在touchesMoved()中将精灵移动到触摸的位置> 如果设置了标志,然后在 touchesEnded() 中重置标志.

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
    }
}    

这篇关于精灵节点位置不随触摸更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆