0
votes

I'm using SpriteKit for a game where there is a ball and a character. The character is moving in a line with SKAction and the user can move the ball by touch. When the ball and character makes contact, I'd like the ball to be attached to the character.

func didBeginContact(contact: SKPhysicsContact) {
     if contact.bodyA.categoryBitMask == charMask && contact.bodyB.categoryBitMask == ballMask{
        println("contact")
        if contactMade {
            let movingBall = contact.bodyB.node!.copy() as! SKSpriteNode
            //this line of code doesn't affect anything no matter what coordinates i set it to
            movingBall.position = contact.bodyA.node!.position
            contact.bodyB.node!.removeFromParent()
            contact.bodyA.node!.removeAllActions()
            contact.bodyA.node!.addChild(movingBall)

        }
    }
}

The current issue is that when I do contact.bodyA.node!.addChild(ball) (character node), the ball gets attached to the far left side of the character instead of on the character and it seems setting movingball.position does not affect it. I've also tried doing addChild to the scene and although it adds the ball to the correct place, it doesn't move with the character without another SKAction. What did I do wrong/what can I do to fix it?

Also, instead of using 2 sprites like that, should I use separate sprites so that theres a character sprite without a ball, character sprite with a ball and the ball itself, then just change the node's texture when they contact?

1
Make sure you're using SKAction to change the ball position.Micrified

1 Answers

0
votes

as movingBall is to be a child of bodyA.node, it's position needs to be in bodyA.node's coordinate space. So if you gave it coordinates of (0,0) it'd be in the middle:

Replace:

movingBall.position = contact.bodyA.node!.position

with

movingBall.position = CGPointZero

and see how that looks. the ball should be positioned directly on top of bodyA.node.