我正在使用 spritekit 制作一个快速游戏,其中我刚刚向场景中添加了一个 SKSpriteNode 图像。当游戏开始时,我想让它在 x 轴上从屏幕左侧移动到右侧,永远重复。我正在努力解决这个问题的代码应该是什么。
我的图像的代码是:
func addDrake1(){
let Drake1 = SKSpriteNode(imageNamed: "Drake1")
Drake1.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height - 300)
Drake1.zPosition = 2
addChild(Drake1)
}
最佳答案
如果你从最左边的 cgpoint(x: 0, y:frame.size.height - 300) 开始 Sprite 位置
你可以使用这个方法:
func moveSprite() {
let moveRight = SKAction.moveByX(frame.size.width, y: 0, duration: 2)
let moveLeft = SKAction.moveByX(-frame.size.width, y: 0, duration: 2)
let moveBackAndForth = SKAction.repeatActionForever(SKAction.sequence([moveRight, moveLeft]))
Drake1.runAction(moveBackAndForth)
}
您还可以通过更改 moveLeft 和 moveRight Action 的持续时间来更改 Sprite 移动的速度
关于swift - 如何让 SKSprite 节点在游戏开始时自行左右移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721186/