My scene has a bunch of rectangles with physics bodies that are the same size as the rectangle. I like to anchor all of my objects to CGPointZero, however I\'ve noticed when
Swift 4.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)
Use default anchor point and it should solve your problem. I had the same problem and I had to programmatically set anchor point to x: 0.5 and y: 0.5 for every physics body in scene. This solved my problems.
I have run in to this myself when using SpriteKit. Unfortunately there appears to be issues based on the timing of creating a physics body and actually adding the node to the scene. If you swap the order from your code and ensure you don't do ANY physics changes until the node is actually in the render tree, that should resolve the 'weirdness' and everything will be all gravy.
I am using Swift but the SKPhysicsBody
was kind of half width and height wrong. I am using anchor point(0,0). Then I used the method with rectangleOfSize
, center
:
var cc = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(32, 64))
cc.physicsBody = SKPhysicsBody(rectangleOfSize: cc.size, center: CGPointMake(32/2, 64/2))
I hope it works for you too guys...thanks !
You need the anchorPoint only when you set your spriteNode's position. I don't quite understand why would you need to move physicsBody (which is the same size of node, I presume) to a corner... But you might find useful this class method [SKPhysicsBody bodyWithPolygonFromPath:path].
Here is a nice generator for that: http://dazchong.com/spritekit/
You can use
[SKPhysicsBody bodyWithRectangleOfSize:size center: center];
CGPoint center = CGPointMake(size.width*(anchorPoint.x-0.5f), size.height*(0.5f-anchorPoint.y))
should transform the bounding box according to the anchorPoint of the parents node