Physicsbody doesn't adhere to node's anchor point
I wrote this to fix Apple's lack thereof:
use pathForRectangleOfSize:withAnchorPoint:
to replace your call to bodyWithRectangleOfSize:
whose brief documentation tells us the problem: "Creates a rectangular physics body centered on the owning node’s origin."
@implementation SKPhysicsBody (CWAdditions)+ (CGPathRef)pathForRectangleOfSize:(CGSize)size withAnchorPoint:(CGPoint)anchor { CGPathRef path = CGPathCreateWithRect( CGRectMake(-size.width * anchor.x, -size.height * anchor.y, size.width, size.height), nil); return path;}+ (SKPhysicsBody *)bodyWithRectangleOfSize:(CGSize)size withAnchorPoint:(CGPoint)anchor { CGPathRef path = [self pathForRectangleOfSize:size withAnchorPoint:anchor]; return [self bodyWithPolygonFromPath:path];}@end
Edit: There is a new API in 7.1 to provide for this oversight.
+ (SKPhysicsBody *)bodyWithRectangleOfSize:(CGSize)s center:(CGPoint)center
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
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 !