SKPhysicsBody not as expected

2019-07-07 16:24发布

问题:

I have the following code to create a rectangular brick and a physics body associated with it. I expected the physics body to be a solid rectangle same size and position as that of the brick, but am getting a body which I think has a poition offset and perhaps also a size difference. Is there some issue with the coordinate systems I have missed? What is the right way to approach this?

- (void)addBrick {
    SKShapeNode *brick = [[SKShapeNode alloc] init];

    CGRect brickBoundary = CGRectMake(0.0, 0.0, 100.0, 100.0);
    brick.position = CGPointMake(100.0, 100.0);
    brick.path = CGPathCreateWithRect(brickBoundary, nil);

    brick.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100.0,100.0)];
    brick.physicsBody.restitution = 1.0;
    brick.physicsBody.friction = 0.0;
    brick.physicsBody.dynamic = NO;

    [self addChild:brick]; 
}

回答1:

This is easy way to create a rect and add a physics body to it.

SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 200);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:n1.size];
n1.physicsBody.dynamic = NO;
[self addChild:n1];

Here is a modified version from a RW tutorial to provide your spite with a debug rect

// RW Debug modified version
CGPathRef bodyPath = CGPathCreateWithRect( CGRectMake(-n1.size.width/2, -n1.size.height/2, n1.size.width, n1.size.height),nil);
SKShapeNode *shape = [SKShapeNode node];
shape.path = bodyPath;
shape.strokeColor = [SKColor colorWithRed:1.0 green:0 blue:0 alpha:0.5];
shape.lineWidth = 1.0;
[n1 addChild:shape];
CGPathRelease(bodyPath);

You implementation produced this (red being the physics box).