我正在开发一个类似于乒乓球的游戏,在开始游戏时,我向随机方向的球施加脉冲,该方向位于屏幕的中心,例如
func impulse(){
let randomNum:UInt32 = arc4random_uniform(200)
let someInt:Int = Int(randomNum)
//Ball Impulse
if someInt<49{
ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+3, dy: ballSpeed-5))
}else if someInt<99{
ball.physicsBody?.applyImpulse(CGVector(dx: ballSpeed+5, dy: -ballSpeed+5))
}else if someInt<149{
ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-5, dy: -ballSpeed+5))
}else if someInt<200{
ball.physicsBody?.applyImpulse(CGVector(dx: -ballSpeed-3, dy: ballSpeed-5))
}
}
其中 ballSpeed 是球的预设速度。那么有什么方法可以在球运动时随着时间的推移逐渐增加球的速度?由于球会不断在屏幕上弹跳,因此很难使用 dx 和 dy 对其施加力。
编辑 -
我使用上述方法只是在游戏开始时为球分配一个随机象限/方向。
开始,当实施脉冲方法时,例如游戏开始图像
我想在游戏过程中随着时间的推移通过预定义的单位增加球的速度,例如游戏
好的,给你!无论如何,球总是变得更快!!!调整amount
以确定球每帧获得多少速度。
class GameScene: SKScene, SKPhysicsContactDelegate {
let ball = SKShapeNode(circleOfRadius: 20)
var initialDY = CGFloat(0)
var initialDX = CGFloat(0)
override func didMove(to view: SKView) {
self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
self.physicsWorld.gravity = CGVector.zero
// Configure ball pb:
let pb = SKPhysicsBody(circleOfRadius: 20)
ball.physicsBody = pb
addChild(ball)
pb.applyImpulse(CGVector(dx: 10, dy: 10))
}
override func update(_ currentTime: TimeInterval) {
initialDX = abs(ball.physicsBody!.velocity.dx)
initialDY = abs(ball.physicsBody!.velocity.dy)
}
override func didSimulatePhysics() {
guard let pb = ball.physicsBody else { fatalError() }
// decrease this to adjust the amount of speed gained each frame :)
let amount = CGFloat(5)
// When bouncing off a wall, speed decreases... this corrects that to _increase speed_ off bounces.
if abs(pb.velocity.dx) < abs(initialDX) {
if pb.velocity.dx < 0 { pb.velocity.dx = -initialDX - amount }
else if pb.velocity.dx > 0 { pb.velocity.dx = initialDX + amount }
}
if abs(pb.velocity.dy) < abs(initialDY) {
if pb.velocity.dy < 0 { pb.velocity.dy = -initialDY - amount }
else if pb.velocity.dy > 0 { pb.velocity.dy = initialDY + amount }
}
}
}
您可以将其修改为每 5 秒仅提高一次速度,SKAction.repeatForever(.sequence([.wait(forDuration: TimeInterval, .run( { code } )))
但 IMO 让它不断提高速度会更棒,更容易实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句