David G. David G. - 4 months ago 24
Swift Question

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
scaleMode
s 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)

Answer

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