gpt4 book ai didi

swift - 如何在不接触 Swift 的情况下拖动 SKSpriteNode

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:24 26 4
gpt4 key购买 nike

我试图通过拖动水平移动 SKSpriteNode。要了解我尝试实现的目标,您可以 watch this .我希望玩家能够在不触摸 Sprite 的情况下拖动它。但我真的不知道如何正确实现它。我尝试做类似的事情:

 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 找到的代码需要“查看”并给我一个错误。我还想限制 Sprite 不应通过的最小和最大位置。 有什么想法可以实现吗?

最佳答案

您可能会遇到该错误,因为您不能只从树中的任何节点访问 View 。您可以将其称为 scene!.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 两个方向上移动 Sprite ,请记住从 View 中反转 y 值(在 View 中向上在场景中向下)。

关于swift - 如何在不接触 Swift 的情况下拖动 SKSpriteNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31928324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com