AndrewShmig
AndrewShmig

Reputation: 4923

Incorrect work of SKPhysicsBody with moved SKSpriteNode anchorPoint?

Here is my code:

    // setting background
_ground = [[SKSpriteNode alloc]
                         initWithColor:[SKColor greenColor]
                                  size:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.name = @"ground";
_ground.zPosition = 1;
_ground.anchorPoint = CGPointMake(0, 0);
_ground.position = CGPointMake(0, 0);
_ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.physicsBody.dynamic = NO;
_ground.physicsBody.affectedByGravity = NO;
_ground.physicsBody.categoryBitMask = groundCategory;
_ground.physicsBody.collisionBitMask = elementCategory;
_ground.physicsBody.contactTestBitMask = elementCategory;

Green rectangle positioning is ok, but SKPhysicsBody is not representing this rectangle correctly. It looks like SKPhysicsBody is not "moving" its body according to sprite position and anchorPoint. SKPhysicsBody is moved left for _ground.width points.

What am I doing wrong?

PS. Changing to this (code) solved my problem, but I really dont like this solution, it seems an ugly way to position an element.

_ground.position = CGPointMake([Helpers landscapeScreenSize].width / 2, 0);

+removing:

_ground.position = CGPointMake(0, 0);

Upvotes: 0

Views: 581

Answers (1)

E. Lüders
E. Lüders

Reputation: 1495

I had exactly the same issue yesterday ;) For me I solved this by using the default sprite positioning by SpriteKit. I just set the position and leave the anchor point at it's default. Then you set the physicsbody to the size of the sprite.

Change your code to the following and check if it works:

_ground = [[SKSpriteNode alloc]
                         initWithColor:[SKColor greenColor]
                                  size:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.position = CGPointMake([Helpers landscapeScreenSize].width / 2, 0);
_ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_ground.size];

If you still have no luck with this you can also try to use another initialisation for your sprite (this works in my project). Try it with a texture:

[[SKSpriteNode alloc] initWithTexture:[SKTexture textureWithCGImage:[UIImage imageWithColor:[UIColor whiteColor]].CGImage] color:[UIColor whiteColor] size:CGSizeMake(PLAYER_WIDTH, PLAYER_HEIGHT)];

don't forget to implement the (UIImage*)imageWithColor: method to create a 1x1 pixel image of your desired color for you (see here).

Upvotes: 1

Related Questions