gpt4 book ai didi

swift - 永远移动 Sprite

转载 作者:可可西里 更新时间:2023-11-01 00:58:56 25 4
gpt4 key购买 nike

当我按下屏幕上的按钮时,我试图将 Sprite 向右移动。但是,当我尝试这样做时,我只有将 Sprite 移动到某个点的解决方案。所以...我希望 Sprite 永远向右移动,或者直到我做其他事情。

这是在 Xcode 中使用 SpriteKit 中的 Swift。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

for touch : AnyObject in touches{

let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
let tappeNodeName = tappedNode.name

if tappeNodeName == "Btn"{

player.physicsBody?.velocity = CGVectorMake(0, 0)

let action = SKAction.applyImpulse(CGVectorMake(400, 0), duration: 1)
player.runAction(SKAction.repeatActionForever(action))

print("Touched!")
}
}
}

最佳答案

您可以简单地将您的节点向右移动,直到它确实存在于场景中

class GameScene: SKScene {

private var player: SKSpriteNode!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

guard let touch = touches.first else { return }
let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
if tappedNode.name == "Btn"{
let moveToRight = SKAction.moveToX(self.frame.width + player.frame.width, duration: 5)
player.runAction(moveToRight)
}

}
}

更新:恒速

如果您希望玩家以恒定速度移动,您可以使用此代码。

如您所见,我正在使用space/speed 计算持续时间。您只需要为您的场景找到速度的最佳常数值。

class GameScene: SKScene {

private var player: SKSpriteNode!

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

guard let touch = touches.first else { return }
let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)


let deltaX = self.frame.width + player.frame.width - player.position.x
let speed: CGFloat = 10 // <-- change this to find the best value for you
let duration: NSTimeInterval = NSTimeInterval(deltaX / speed)

if tappedNode.name == "Btn"{
let moveToRight = SKAction.moveByX(deltaX, y:0, duration: duration)
player.runAction(moveToRight)
}

}
}

关于swift - 永远移动 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38749200/

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