在屏幕上移动 SKSpriteNode
Posted
技术标签:
【中文标题】在屏幕上移动 SKSpriteNode【英文标题】:Moving SKSpriteNode over screen 【发布时间】:2015-09-20 14:41:25 【问题描述】:我想通过触摸在屏幕上移动一个 SKSpriteNode。我遇到的问题是,如果我锁定一个精灵然后我的手指将它拖到另一个精灵上,第一个精灵会松开,我的手指开始拖动第二个精灵。但是一旦我触摸到第一个精灵,这是我唯一想要移动的精灵。 必须有一个简单的方法来解决这个问题?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
/* Called when a touch begins */
let touch: UITouch = touches.first as UITouch!
touchLocation = touch.locationInNode(self)
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
let touch: UITouch = touches.first as UITouch!
let newTouchLocation = touch.locationInNode(self)
let targetNode = self.nodeAtPoint(touchLocation)
if targetNode.physicsBody!.categoryBitMask != PhysicsCategory.Ball
targetNode.runAction(SKAction.moveBy(CGVector(point: newTouchLocation - touchLocation), duration: 0.0))
touchLocation = newTouchLocation
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
//I don't do anything with this yet
【问题讨论】:
【参考方案1】:发生这种情况是因为每次您的手指移动时您的 touchesMoved 函数都会运行,并且如果您的手指移动到一个新节点上,该节点将被分配给 targetNode。您可以通过更改此行来解决此问题:
let targetNode = self.nodeAtPoint(touchLocation)
到这里:
let targetNode = self.nodeAtPoint(touch)
这样,第一次触摸时的节点将跟随您的手指,而不是最后一次触摸时的节点。
【讨论】:
它不起作用-“无法将'UITouch'类型的值转换为预期的参数类型'CGPoint'”【参考方案2】:感谢 TheCodeComposer,我找到了解决方案:
var targetNode: SKNode!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
/* Called when a touch begins */
let touch: UITouch = touches.first as UITouch!
touchLocation = touch.locationInNode(self)
targetNode = self.nodeAtPoint(touchLocation)
objectTouched(touch.locationInNode(self))
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
let touch: UITouch = touches.first as UITouch!
let newTouchLocation = touch.locationInNode(self)
// let targetNode = self.nodeAtPoint(touchLocation)
if targetNode.physicsBody!.categoryBitMask != PhysicsCategory.Ball
targetNode.runAction(SKAction.moveBy(CGVector(point: newTouchLocation - touchLocation), duration: 0.0))
touchLocation = newTouchLocation
我只定义
目标节点
一次然后继续使用它而不是在touchesMoved中重新定义它:
【讨论】:
以上是关于在屏幕上移动 SKSpriteNode的主要内容,如果未能解决你的问题,请参考以下文章