当我按下屏幕上的按钮时,我正试图将精灵移动到右侧。但是,当我尝试这样做时,我只有一个解决方案将精灵移动到某一点。所以...我希望精灵永远向右移动或直到我做其他事情。
这是在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!")
}
}
}
答案 0 :(得分:3)
您可以简单地将节点向右移动,直到场景中存在
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)
}
}
}