Search code examples
iosswiftsprite-kitskphysicsbody

Is it possible to position physicsbody to only one part of the Sprite?


Is it possible to position a physics body on a sprite? I only want a certain part of my sprite node to have collision detection, not the whole image.

Heres my physics body

physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: CGFloat(54.0), height: CGFloat(100.0)))

But i want to position the physics body at the top of the node, where it usually gets placed in the middle of the node.


Solution

  • You can try creating a smaller SKSpriteNode of the same size as the SKPhysicsBody and adding the larger SKSpriteNode as a child to the smaller one. Changing the position of the larger one as you want. For example

    override func didMoveToView(view: SKView) {
    
        let smallerSprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(30, 30))
        smallerSprite.physicsBody = SKPhysicsBody(rectangleOfSize: smallerSprite.size)
        smallerSprite.position = CGPointMake(100, 400)
        self.addChild(smallerSprite)
    
        let largerSprite = SKSpriteNode(color: UIColor(white: 0.5, alpha: 0.5), size: CGSizeMake(100, 100))
        largerSprite.position = CGPointMake(-10, -10)
        smallerSprite.addChild(largerSprite)
    
        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
    
    }