How to make physics bodies stick to nodes anchor points
Asked Answered
D

1

2

I have four squares in the middle of my scene set up with various anchor points. When tapped, they move together and come apart depending on what position:

 func rotate(angle : CGFloat, animated : Bool) {
    var rotateAction : SKAction!

    if animated {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0.6)
    }
    else {
        rotateAction = SKAction.rotateByAngle(angle, duration: 0)
    }
    for node in self.children as! [SKSpriteNode] {

        node.runAction(rotateAction)
    }
}

}

The problem I have is that that the physics bodies of the nodes are strictly staying on the anchor points and not the nodes themselves which is giving me a mess of problems. How can I make it so that I can have the anchor point that I want for each node and make the physics bodies directly stay on the nodes? Will post more code if necessary.

Dubitable answered 3/1, 2016 at 20:25 Comment(0)
C
11

You need to apply the anchor point to the physics body, it has no understanding of what sprite is, it is just another piece of information sprite uses, so use the following calculation to determine where the center of the sprite should be, and apply that to the physics body so that it may shift:

 let centerPoint = CGPointMake(sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size, center: centerPoint)

Swift 3+:

 let centerPoint = CGPoint(x:sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), y:sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
 sprite.physicsBody = SKPhysicsBody(rectangleOf: sprite.size, center: centerPoint)

Less text:

 let centerPoint = CGPoint(x:sprite.size.width * (0.5 - sprite.anchorPoint.x), y:sprite.size.height *(0.5 - sprite.anchorPoint.y))
Commove answered 4/1, 2016 at 2:40 Comment(1)
swift4.1 let centerPoint = CGPoint(x: house1.size.width / 2 - (house1.size.width * house1.anchorPoint.x), y: house1.size.height / 2 - (house1.size.height * house1.anchorPoint.y)) house1.physicsBody = SKPhysicsBody(rectangleOf: house1.size, center: centerPoint)Vertex

© 2022 - 2024 — McMap. All rights reserved.