第一次球射得太快

Ball shot too fast the first time

我有一个代表炮弹的精灵,我用这种方法射击它:

func shoot() {
    let ball = Ball(radius: 8.0)
    ball.position = CGPointMake(size.width / 2.0, 72.0)
    self.addChild(ball)


    // Explosion is just a simple particle system
    let explosion = Explosion() 
    explosion.position = CGPointMake(size.width / 2.0, 64.0)
    self.addChild(explosion)

    let force = CGVectorMake(0.0, 20000.0)
    ball.physicsBody!.applyForce(force)
}

球是一个质量为 1.0 的物体,创建方式如下:

init(radius: CGFloat) {
    super.init()

    let path = UIBezierPath(arcCenter: CGPointZero, radius: radius, startAngle: 0.0, endAngle: 2.0 * PI, clockwise: false)
    self.path = path.CGPath
    self.strokeColor = SKColor.blackColor()
    self.fillColor = SKColor.blackColor()

    self.name = "Ball \(self)"

    let body = SKPhysicsBody(circleOfRadius: radius)
    body.dynamic = true
    body.categoryBitMask = BallCategory
    body.contactTestBitMask = EnemyCategory
    body.collisionBitMask = EnemyCategory
    body.mass = 1.0
    body.affectedByGravity = false
    physicsBody = body
}

问题是我第一次(也是第一次)射球的速度非常快。所有其他时间他们都有不同的、较低的速度,为什么?

看来您使用 applyForce 的方式有误。来自文档:

A force is applied for a length of time based on the amount of simulation time that passes between when you apply the force and when the next frame of the simulation is processed. So, to apply a continuous force to an body, you need to make the appropriate method calls each time a new frame is processed. Forces are usually used for continuous effects

意味着你必须在 update: 方法中调用 applyForce:。从你的代码中可以看出你没有这样做(shoot() 方法可能在 touchesBegan 内部被调用)。

也来自与 applyForce 方法相关的文档:

The acceleration is applied for a single simulation step (one frame).

关于超快球问题...我有一个理论,但不能确定发生了什么,特别是因为你没有像它的意思那样使用 applyForce,我认为这是主要问题。

所以,这是理论:

每帧之间的时间差可能会有所不同,尤其是当您启动应用程序并且第一次加载内容时,并且由于力乘以该时间差,您会得到奇怪的结果。

另一方面,applyImpulse: 非常适合您的情况。射球是一个瞬时动作,applyImpulse 不像 applyForce 那样依赖于模拟时间(请参阅我发布的文档中的引述)。

解决方法:

使用applyImpulse投篮。这是认可的方式。如果你想用 applyForce 移动球,请在每一帧中通过更新方法进行。

在开始实际游戏之前还要考虑资源预加载(预加载声音、发射器、纹理),这将避免游戏开始时 fps 下降。

希望这对您有所帮助!