Search code examples
swiftsprite-kitskspritenodeskphysicsbodycgpath

Trouble with: SKPhysicsBody(polygonFromPath: CGPath) using Swift and SpriteKit


I am trying to create a physics body for an SKSpriteNode. I usually create the physics body using an image and saying:

snode = SKSpriteNode(imageNamed: snodeImage)
snode = SKPhysicsBody(texture: snode.texture!, size: snode.size)

I would like to be able to create a physics body using:

snode.physicsBody = SKPhysicsBody(polygonFromPath: CGPath)

I have no idea how to do this, I have tried looking online but I can't figure it out. Could somebody please show me a small example? Maybe show me how you would create a simple rectangular physics body using this constructor?


Solution

  • The easiest way to do this is to use UIBezierPath because it has a number of helpful constructors, then convert that to the CGPath that polygonFromPath wants.

    You asked for some code to create a simple rectangular physics body:

    let square = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 128, height: 128))
    square.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
    
    let path = UIBezierPath(rect: CGRect(x: -64, y: -64, width: 128, height: 128))
    square.physicsBody = SKPhysicsBody(polygonFromPath: path.CGPath)
    
    addChild(square)
    

    Note that the physics body is offset because it's measured from the centre of its node. You might want use skView.showsPhysics = true in your GameViewController.swift file to help you debug your physics shapes.