Physicsbody doesn't adhere to node's anchor point

前端 未结 7 1177
陌清茗
陌清茗 2020-12-09 15:09

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

7条回答
  •  囚心锁ツ
    2020-12-09 15:44

    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
    

提交回复
热议问题