nested SKNodes in spritekit?

146 views Asked by At

I would like to make a hollow box, with a number that floats in the middle of it. the box and the number inside should behave according to physics as if the number were attached by springs to all 4 corners (or sides) equally. In my code here, that's not what happens at all. instead, the objects fall apart. also the positioning doesn't seem right.

import SpriteKit

public class BoxNode: SKNode {

    public func setup(size: CGSize, number: Int) {


        let shape = SKShapeNode()
        shape.path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height)).cgPath
        shape.position = CGPoint(x: 0, y: 0)
        shape.fillColor = UIColor.red
        shape.strokeColor = UIColor.blue
        let lineWidth = size.width * 0.05
        shape.lineWidth = lineWidth
        //edge loop of the inside of the path.
        //this idea is probably wrong
        //TODO- figure out how this physicsBody ought to be set up.

        shape.physicsBody = SKPhysicsBody(rectangleOf: shape.frame.size)
//        shape.physicsBody = SKPhysicsBody(edgeLoopFrom: (UIBezierPath(rect: CGRect(x: lineWidth, y: lineWidth, width: size.width - (2 * lineWidth), height: size.height - 2 * lineWidth)).cgPath))
//        
        addChild(shape)
        let numberLabel = SKLabelNode()
        numberLabel.fontName = "Chalkduster"
        numberLabel.text = String(number)
        numberLabel.position = CGPoint(x: size.width / 2, y: size.height / 2)
        numberLabel.verticalAlignmentMode = .center
        numberLabel.horizontalAlignmentMode = .center
        numberLabel.physicsBody = SKPhysicsBody(rectangleOf: numberLabel.frame.size, center: numberLabel.position)
        shape.addChild(numberLabel)
        let spring = SKPhysicsJointSpring()

        guard let bodyA = shape.physicsBody else { return }
        spring.bodyA = bodyA

        guard let bodyB = numberLabel.physicsBody else { return }
        spring.bodyB = bodyB
    }
}
0

There are 0 answers