SKPhysicsBody not as expected

杀马特。学长 韩版系。学妹 提交于 2019-12-12 14:18:00

问题


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).



来源:https://stackoverflow.com/questions/19396279/skphysicsbody-not-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!