3

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
  • size must be half that of frame.size because body rectangle size is the width/height from center to either side, not the total width
    – CodeSmile
    Oct 16, 2013 at 8:51

1 Answer 1

5

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

enter image description here

4
  • Thanks, it worked :). But do you know where is the problem with my implementation?
    – Roshan
    Oct 16, 2013 at 7:01
  • 1
    this fixes your implementation CGRect brickBoundary = CGRectMake(-50, -50, 100.0, 100.0); I assume its because spriteNodes have no anchor point so its set at 0,0 ? I aint totally sure sorry.
    – DogCoffee
    Oct 16, 2013 at 7:20
  • yeah, i think the problem is with the anchor point too... Thanks :)
    – Roshan
    Oct 17, 2013 at 2:11
  • Thank you, it's a great solution. I have updated your code and implemented for a circle. Anybody having troubles about it can check out my blog post: kubilayerdogan.net/…
    – kubilay
    Jun 1, 2014 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.