I have a lot of different sprite nodes with a physicsbody the same size as the object. For positioning I need to change the anchorpoint of the node, but this changes the pos
The anchorPoint
is a purely visual property, it defines how the texture is drawn relative to the node's position. The physics body remains unaffected by changing the anchorPoint
, it remains centered on the node's position
.
So in a sense, the physics body does remain centered on the sprite's position already. By changing the anchorPoint you merely changed where the sprite's texture is displayed, and I believe you assumed the physics body would center on the sprite's anchorPoint. It does not, for one every node can have a physics body but only few nodes (sprite, scene, video) have an anchorPoint property.
The best way to fix this is to create your sprite images so that the physics body is always assumed to be centered on the image. Leave transparent borders around the image to ensure the image size is always the same and the position of the body properly centered.
You can also use SKPhysicsBody bodyWithRectangleOfSize:center:
initializer to define the center point of the body and to match it up with the sprite's anchorPoint. But this is tricky and counterproductive, as you'll have to constantly realign body and sprite anchorPoint if you make even the smallest change.
Other than that it's best to leave the anchorPoint alone, especially with physics.
An old thread but still pops up when I google searched... Here was how I solved the problem for myself.
I essentially just stacked my SKSpriteNodes. The highest level parent node would receive the SKPhysicsBody so that all the objects would stay together. If you add the SKPhysicsBody object as a child to another node, the physicsBody can essentially fall out of the other nodes (images would be left floating in my case) when gravity or other forces are applied and can return some wonky results if you aren't careful.
To further clarify:
This specifically allows you to use a texture based SKPhysicsBody or something more complicated that does not have a centering option. The physicsBody worked just as I needed it to while still being able to manipulate SKActions in the way in which a modified anchor point allows.
Hope this helps someone.