如何拖动SKSpriteNode而不用Swift触摸它
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何拖动SKSpriteNode而不用Swift触摸它相关的知识,希望对你有一定的参考价值。
我试图通过拖动水平移动SKSpriteNode。为了了解我试图实现的目标,你可以watch this。我希望玩家能够在不触碰精灵的情况下拖动精灵。但我真的不知道如何正确实现它。我尝试过这样的事情:
override func didMoveToView(view: SKView) {
/* Setup your scene here */
capLeft.size = self.capLeft.size
self.capLeft.position = CGPointMake(CGRectGetMinX(self.frame) + self.capLeft.size.height * 2, CGRectGetMinY(self.frame) + self.capLeft.size.height * 1.5)
capLeft.zPosition = 1
self.addChild(capLeft)
let panLeftCap: UIPanGestureRecognizer = UIPanGestureRecognizer(target: capLeft, action: Selector("moveLeftCap:"))
当我设置moveLeftCap函数时,我为UIPanGestureRecognizer找到的代码需要“查看”并给我一个错误。我还想限制它不应该通过的精灵的最小和最大位置。任何想法如何实现?
答案
您可能会收到该错误,因为您无法从树中的任何节点访问该视图。您可以将其称为场景!.view或您在场景中处理手势,如果您想要保持简单,这是更好的选择。
我试了一下,想出了这个基本场景:
import SpriteKit
class GameScene: SKScene {
var shape:SKNode!
override func didMoveToView(view: SKView) {
//creates the shape to be moved
shape = SKShapeNode(circleOfRadius: 30.0)
shape.position = CGPointMake(frame.midX, frame.midY)
addChild(shape)
//sets up gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: "panned:")
view.addGestureRecognizer(pan)
}
var previousTranslateX:CGFloat = 0.0
func panned (sender:UIPanGestureRecognizer) {
//retrieve pan movement along the x-axis of the view since the gesture began
let currentTranslateX = sender.translationInView(view!).x
//calculate translation since last measurement
let translateX = currentTranslateX - previousTranslateX
//move shape within frame boundaries
let newShapeX = shape.position.x + translateX
if newShapeX < frame.maxX && newShapeX > frame.minX {
shape.position = CGPointMake(shape.position.x + translateX, shape.position.y)
}
//(re-)set previous measurement
if sender.state == .Ended {
previousTranslateX = 0
} else {
previousTranslateX = currentTranslateX
}
}
}
当您在屏幕上移动手指时,圆圈会相应地沿x轴移动。
如果你想在x和y方向上移动精灵,请记住从视图中反转y值(在视图中向上是在场景中向下)。
以上是关于如何拖动SKSpriteNode而不用Swift触摸它的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 SKPhysicsJointPin 连接两个 SKSpriteNode - swift
移动时如何访问 SKSpriteNode 子类的对象(Swift)
SKSpriteNode 从场景中移除后如何停止音频(Swift)?