SKPhysicsBody Change Center of Mass

牧云@^-^@ 提交于 2019-12-14 01:29:54

问题


I am currently working on a game where I have a picture of a kind of cylindrical object, and I make an SKPhysicsBody with the following:

self.oval.node.physicsBody = SKPhysicsBody(texture: self.oval.node.texture, size: self.oval.node.size)

This method creates a nice shape around the node, however, the center of gravity is way off... It balances on the tip of the oval. Is there anyway to change that so it balances where the heaviest part should in theory be? Thanks!


回答1:


The center of mass can't be way off, it is exact. The problem is you want your physics body to have a non-uniform density. The density of a rigid physics body is uniform throughout. I don't see a way of doing this other than modifying the physics body itself (i.e. Changing the size/shape of the physics body).

Even if you try creating a physics body from the union of multiple physics bodies using SKPhysicsBody(bodies: [body1,body2]) the density will still be uniform because Sprite Kit will still simulate this as just one body.

The only solution I can think of is to fuse 2 bodes together using a joint as shown below.

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let node1 = SKShapeNode(circleOfRadius: 20)
        node1.physicsBody = SKPhysicsBody(circleOfRadius: 20)
        node1.position = CGPoint(x: self.size.width/2.0, y: self.size.height/2.0)

        let node2 = SKShapeNode(circleOfRadius: 2)
        node2.physicsBody = SKPhysicsBody(circleOfRadius: 1)
        node2.position = CGPoint(x: self.size.width/2.0, y: self.size.height/2.0+19)
        node2.physicsBody!.mass = node1.physicsBody!.mass * 0.2 //Set body2 mass as a ratio of body1 mass.

        self.addChild(node1)
        self.addChild(node2)

        let joint = SKPhysicsJointFixed.jointWithBodyA(node1.physicsBody!, bodyB: node2.physicsBody!, anchor: node1.position)

        self.physicsWorld.addJoint(joint)

        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        node1.physicsBody!.applyImpulse(CGVector(dx: -10, dy: 0))
    }
}

However this won't fix the special case where the circle lands perfectly centered. You see I apply an impulse to temporarily solve the issue in the code above. A better solution is to check for this special case in the update method.


Note the gif got cut off a little at the bottom.



来源:https://stackoverflow.com/questions/31664505/skphysicsbody-change-center-of-mass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!