在重力下旋转物体

时间:2016-11-01 13:54:34

标签: ios swift sprite-kit

我试图创建一个有径向重力场的场景。在这个场景中,还有一个物体由两个不同质量的物理体构建。

当我运行此代码时,径向重力场被正确创建,并且主体进入gravityCenter。 我期待身体旋转,因为头部比尾部重,但这并没有发生。

为什么?

class GameScene: SKScene {

    let object = SKSpriteNode(imageNamed: "myobj")

    let myCategory : UInt32 = 0x1 << 0

    override func didMove(to view: SKView) {
        self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)

        let gravityCenter = SKFieldNode.radialGravityField()
        gravityCenter.isEnabled = true
        gravityCenter.position = CGPoint(x: size.width, y: size.height * 0.5)
        gravityCenter.strength = 0.5
        addChild(gravityCenter)

        object.position = CGPoint(x: size.width * 0.1, y: size.height * 0.9)
        object.scale(to: CGSize(width: 100, height: 25))

        let head = SKPhysicsBody(circleOfRadius: object.size.width/5, center: CGPoint(x: object.size.width/2, y: 0))
        let tail = SKPhysicsBody(circleOfRadius: object.size.width/50, center: CGPoint(x: -object.size.width/2, y: 0))

        head.mass = 500
        head.categoryBitMask = myCategory
        head.allowsRotation = true
        head.isDynamic = true
        head.angularDamping = 0
        head.affectedByGravity = true

        tail.mass = 2
        tail.categoryBitMask = myCategory
        tail.allowsRotation = true
        tail.isDynamic = true
        tail.angularDamping = 0
        tail.affectedByGravity = true

        object.physicsBody = SKPhysicsBody(bodies: [head, tail])
        object.physicsBody?.categoryBitMask = myCategory
        object.physicsBody?.allowsRotation = true
        object.physicsBody?.isDynamic = true
        object.physicsBody?.angularDamping = 0
        object.physicsBody?.affectedByGravity = true

        addChild(object)
    }
}

1 个答案:

答案 0 :(得分:2)

嗯,从物理学角度来看,SpriteKit表现正常。如果你考虑一下,更多质量 意味着更多的引力,但它也意味着更多的惯性,这恰好抵消了增加的力量。也许在尾部引入一点linearDamping?通过让头部稍稍拖动尾部,可以使身体旋转。