Search code examples
swiftsprite-kitskphysicsbodyskshapenode

Swift 3 (SpriteKit): Aligning SKPhysicsBody to SKShapeNode


I am creating SKShapeNodes in my program using this:

let points = [CGPoint(x: x, y: y), CGPoint(x: x2, y: y2)]
let line = SKShapeNode(points: &points, count: points.count)

The problem that I am having is that whenever I add a physicsBody to the line, the physicsBody is not aligned with the line. I realise that the issue is because the line's position is always CGPoint(x: 0, y: 0) so the physicsBody is always in the centre of the screen regardless of where the line is. Here is my code for creating the physicsBody:

line.physicsBody = SKPhysicsBody(rectangleOf: (line.frame.size))

If anyone knows how to align the physicsBody to the line, then please reply with your solution. Thanks!


Solution

  • If you want to make a physics body from one point to the other, you may use something like this:

    class GameScene:SKScene {
    
        override func didMove(to view: SKView) {
            var points = [CGPoint(x: 22, y: 22), CGPoint(x: 155, y: 155)]
            let line = SKShapeNode(points: &points, count: points.count)
            print(line.frame.size)
    
            line.physicsBody = SKPhysicsBody(edgeFrom: points[0], to: points[1])
    
            addChild(line)
        }
    }
    

    This will create an edge based physics body using two points. An edge physics body is static by default so keep that in mind. To register a contact (or make a collision with this body) the other body has to be dynamic.

    If you want to have this body dynamic, then look for volume based initializers.