2

I would like two regions, as shown in the image below, where the yellow region is to contain sprites. For example I'd like to have balls in the yellow region bouncing and reflecting off the boundaries of the yellow region. How can I programmatically do this without using an sks file?

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
spigen
  • 81
  • 1
  • 7

1 Answers1

3

You create an edge based physics body using the +bodyWithEdgeLoopFromRect:

override func didMoveToView(view: SKView) {

    //Setup scene's physics body (setup the walls)
    physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)

    let yellowSprite = SKSpriteNode(color: .yellowColor(), size: CGSize(width: 300, height: 300))
    yellowSprite.position = CGPoint(x: frame.midX, y: frame.midY)

    //Create the rectangle which will represent physics body.
    let rect = CGRect(origin: CGPoint(x: -yellowSprite.size.width/2, y: -yellowSprite.size.height/2), size: yellowSprite.size)
    yellowSprite.physicsBody = SKPhysicsBody(edgeLoopFromRect: rect)

    addChild(yellowSprite)

    //Add Red ball "inside" the yellow sprite
    let red = SKShapeNode(circleOfRadius: 20)
    red.fillColor = .redColor()
    red.strokeColor = .clearColor()
    red.position = yellowSprite.position
    red.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    red.physicsBody?.restitution = 1
    red.physicsBody?.friction = 0
    red.physicsBody?.affectedByGravity = false

    addChild(red)

    red.physicsBody?.applyImpulse(CGVector(dx: 20, dy: 15))

}

About rect parameter:

The rectangle that defines the edges. The rectangle is specified relative to the owning node’s origin.

Hope this helps!

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • Perfect, thank you! I've added red.physicsBody?.linearDamping = 0 and the ball is in perfect reflection. – spigen Feb 03 '16 at 18:53