gpt4 book ai didi

ios - 如何用手指移动 Sprite ?

转载 作者:行者123 更新时间:2023-11-28 05:31:01 24 4
gpt4 key购买 nike

我希望能够用手指移动 Sprite 。我首先有一个变量来判断手指是否在 Sprite 上:

var isFingerOnGlow = false

然后我有 touchesBegan 函数,如果用户触摸 Sprite ,我会更改上述变量的值:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var touch = touches.anyObject() as UITouch!
var touchLocation = touch.locationInNode(self)

if let body = physicsWorld.bodyAtPoint(touchLocation) {
if body.node!.name == GlowCategoryName {
println("Began touch on hero")
isFingerOnGlow = true
}
}
}

有时可以,控制台显示“begin touch on hero”,有时则不行。有没有更好的方法来编写第一部分的代码?

然后我想知道我下面的touchesMoved代码是否有效:

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
if isFingerOnGlow{
var touch = touches.anyObject() as UITouch!
var touchLocation = touch.locationInNode(self)
var previousLocation = touch.previousLocationInNode(self)

var glow = SKSpriteNode(imageNamed: GlowCategoryName)

// Calculate new position along x for glow
var glowX = glow.position.x + (touchLocation.x - previousLocation.x)
var glowY = glow.position.y + (touchLocation.y - previousLocation.y)

// Limit x so that glow won't leave screen to left or right
glowX = max(glowX, glow.size.width/2)
glowX = min(glowX, size.width - glow.size.width/2)

glow.position = CGPointMake(glowX, glowY)
}
}

...

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
isFingerOnGlow = false
}

最佳答案

您可以像这样修改函数来跟踪触摸。

var isFingerOnGlow = false
var touchedGlowNode : SKNode!


override func touchesBegan(touches: NSSet, withEvent event:UIEvent) {
var touch = touches.anyObject() as UITouch!
var touchLocation = touch.locationInNode(self)

let body = self.nodeAtPoint(touchLocation)
if body.name == GlowCategoryName {
println("Began touch on hero")
touchedGlowNode = body
isFingerOnGlow = true
}

}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

if isFingerOnGlow{

let touch = touches.anyObject() as UITouch!
let touchLocation = touch.locationInNode(self)
let previousLocation = touch.previousLocationInNode(self)
let distanceX = touchLocation.x - previousLocation.x
let distanceY = touchLocation.y - previousLocation.y

touchedGlowNode.position = CGPointMake(touchedGlowNode.position.x + distanceX,
touchedGlowNode.position.y + distanceY)
}
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
isFingerOnGlow = false
}

关于ios - 如何用手指移动 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436078/

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