David Gourde
David Gourde

Reputation: 3914

Frame of SKShapeNode is offset

I am trying to add a physicsBody to an SKShapeNode that is a rectangle. I built my PhysicsBody using fromEdgesWithLoop using the Node's frame as the CGRect to build it.

Using the debug option to show PhysicsBody, I see that it is actually not centered on my Sprite.

PhysicsBody is offset

I searched the web to find that I should use this:

scene.scaleMode = .ResizeFill

Sadly, I tried all scaleModes and there are no differences.

I also verified my GameScene's size and it fits the iPad2 screen (my target), 1024x720.

The SKShapeNode is a child of the Scene.

I tried to set the position of my node in the center of the Scene before adding a PhysicsBody with its frame, but this changed nothing. The node was already in the center of the scene.

myShape.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
myShape.physicsBody = SKPhysicsBody(edgeLoopFromRect: myShape.frame)

Upvotes: 1

Views: 683

Answers (1)

0x141E
0x141E

Reputation: 12753

The position of an Edge Loop is relative to the node it's attached to. In general, for an edgeLoopFromRect, the position is given by

edge_loop_position = node.position + rect.frame.origin

In this case, your physics body is offset by the position of myShape. One way to fix this issue is to attach the edge loop to the scene instead of the shape node:

self.physicsBody = SKPhysicsBody(edgeLoopFromRect: myShape.frame )

Alternatively, you can subtract the node's position from the frame's position with

let rect = CGRect(origin:CGPoint(x:myShape.frame.origin.x-myShape.position.x, y:myShape.frame.origin.y-myShape.position.y), size:myShape.frame.size)
myShape.physicsBody = SKPhysicsBody(edgeLoopFromRect:rect)

Upvotes: 3

Related Questions