我正在 Swift Playground 上制作一个小型 SpriteKit 游戏,它是一种小行星防御类型的游戏。基本上,玩家是用大炮保卫航天器,必须摧毁接近的岩石。下面的图片链接是我还没有添加枪支的场景,但基本上我希望岩石从顶部慢慢向下移动到底部的航天器(抱歉,它太大了,无法添加到这里)。
https://www.dropbox.com/s/pisgazar4jaxra0/Screenshot%202017-03-18%2011.23.17.png?dl=0
岩石将是 SKSpriteNodes,我想为每个连续的岩石加速它们以随着时间的推移增加难度。
我将如何实现它。我在其他地方看到了一些关于使用 UIBezierPaths 的答案,但是我如何让它随机但限制岩石只能从上面掉下来?
提前致谢!
最佳答案
如果你只需要它们从上到下移动而没有任何特殊的弯曲轨迹,那么你不需要处理样条。
让我们先解决逐渐加速的问题。您希望它们在开始时缓慢下落,并在游戏过程中加速。一种方法是跟踪关卡时间并根据经过的关卡时间进行一些持续时间计算。一种更简单的方法是减少小行星到达底部所需的时间。在你的场景声明部分,声明那些:
fileprivate let startingDuration: TimeInterval = 6.0 // Put here whatever value you feel fit for the level start falling speed
fileprivate let difficultyIncrease: TimeInterval = 0.05 // Put here whatever value you feel fit for how much should each next asteroid accelerate
fileprivate let collisionPosition = CGPoint(x: 300, y: 200) // Put here the onscreen location where the asteroids should be heading to
fileprivate var asteroidCounter = 0 // Increase this counter every time you spawn a new asteroid
现在,让我们来看看实际的小行星运动。有不同的方法来处理它。 Apple 推荐的最简单的方法是为此使用一个操作。将此代码添加到您的小行星生成方法中:
// Implement here your spawning code ...
// It's best to choose random starting points (X axis) a bit higher than the upper screen boundary
let fallingDuration: TimeInterval = startingDuration - difficultyIncrease * TimeInterval(asteroidCounter)
let fallingAction = SKAction.move(to: collisionPosition, duration: fallingDuration)
asteroid.runAction(fallingAction)
如果你需要一个随机整数生成函数,试试这个:
func RandomInt(min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max-(min-1)))) + min
}
关于swift - Swift 中具有约束的 SKSpriteNode 的随机向下运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42876209/