1

The SKSpriteNode anchor point is set to (0.5, 0).

How can you create a physics body with SKPhysicsBody(texture: size:) centered at (0.5,0.5), without changing the (0.5, 0) anchor point.

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
crvo84
  • 303
  • 2
  • 11

1 Answers1

2

You can use + bodyWithRectangleOfSize:center: or + bodyWithCircleOfRadius:center:, like this:

 let sprite = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: 100.0, height: 100.0))
 sprite.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
 sprite.anchorPoint = CGPoint(x: 0.5, y: 0.0)

 sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size, center: CGPoint(x: 0, y: sprite.size.height/2.0))
 sprite.physicsBody?.affectedByGravity = false // just added for easier debugging
 addChild(sprite)

Center parameter represents the origin of the square/circle in the owning node’s coordinate system.

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • I need to use SKPhysicsBody(texture: size:) to get a body with the shape of the texture but with a different size. – crvo84 Nov 03 '15 at 20:49
  • @crvo84 Ah, okay...So, what is the reason of changing node's anchor point ? Can't you just leave it as (0.5,0.5) and change node's position accordingly ? – Whirlwind Nov 03 '15 at 22:31
  • 1
    One useful post about anchorPoint & physicsBody. http://stackoverflow.com/a/22095999/3402095 – Whirlwind Nov 03 '15 at 22:39
  • Inside the scene, I need to rotate the sprite around the anchor point at (0.5, 0). It would be great if there is a way to change the body center so I would not need to change all my code accordingly. thanks! – crvo84 Nov 04 '15 at 00:57