斯威夫特:设定距离

时间:2016-03-02 16:28:56

标签: ios swift game-physics skphysicsbody

我试图在Swift上创建一个移动平台,为了让玩家与平台一起移动,我需要将self.moveByX()更改为{physicsBody?.velocity更简单1}}(并为平台和玩家添加一些摩擦力)。

所以,我做了这样一个函数:

self.runAction(
    SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock({
                print(self.position.x)
                self.physicsBody?.velocity = CGVectorMake(20, 0.0)
            }),
            SKAction.waitForDuration(3),
            SKAction.runBlock({
                print(self.position.x)
                self.physicsBody?.velocity = CGVectorMake(-20, 0.0)
            }),
            SKAction.waitForDuration(3)
        ])
    )
)

问题在于我预计这些位置之间的差异恰好是60(20 * 3s),但是我接收了平台x位置的日志,如下所示:

596.042907714844
544.228393554688
596.048950195312
544.234008789062
596.054565429688
544.116333007812
595.936584472656
544.121887207031
595.942199707031
544.127685546875
595.824584960938
544.009704589844

因此,这些位置之间的差异在51~52之间。

如何通过改变速度让平台在特定和精确的距离内移动?

编辑:我不知道这是否相关,但我已经设置了平台的物理机构:

self.physicsBody = SKPhysicsBody(rectangleOfSize: self.size)
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
self.physicsBody?.collisionBitMask = PhysicsCategory.Player
self.physicsBody?.allowsRotation = false
self.physicsBody?.affectedByGravity = false
self.physicsBody?.dynamic = true
self.physicsBody?.friction = 1.0
self.physicsBody?.restitution = 0.0
self.physicsBody?.mass = 99999999999

1 个答案:

答案 0 :(得分:2)

我之前没有使用过Sprite Kit,但我认为你的问题是SKPhysicsBody的linearDamping属性默认设置为0.1,快速计算(20 * 3-20 * 3 * 0.1 = 54如果每帧阻尼速度,这听起来是正确的。

以下是该属性的文档:

https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/index.html#//apple_ref/occ/instp/SKPhysicsBody/linearDamping

编辑:我认为至少应该检查我的答案,所以我写了一个快速(粗略)程序:

var dampingOccurancesPerSecond = 60.0 //Corresponds to frame rate
var numberOfSeconds = 3.0
var time = 0.0

@IBAction func test(sender: UIButton) {
    let result = checkDistanceForVelocity(20, damping: 0.1, distanceTraveled: 0.0)
    print(result)
}

 func checkDistanceForVelocity(velocity: Double, damping: Double, distanceTraveled: Double) -> Double {

    if time < numberOfSeconds {

        time += 1/dampingOccurancesPerSecond

        let newVelocity = velocity - (velocity * damping/dampingOccurancesPerSecond)

        let newDistance = (distanceTraveled + velocity/dampingOccurancesPerSecond)

        return checkDistanceForVelocity(newVelocity, damping: damping, distanceTraveled: newDistance)

    }

    return distanceTraveled

}

您的行进距离的微小变化也可能是由于您的帧速率的微小变化。当dampingOccurancesPerSecond从60改变时,&gt; 50总行驶距离从52.1203109538336变化 - &gt; 51.8808576268828

希望这有帮助!!