Santiago Moreno
Santiago Moreno

Reputation: 113

using skphysicsBody and circle of radius to trap ball in circle

skphysics and

    roundbg.physicsBody = SKPhysicsBody(circleOfRadius: round.frame.width/2)
    roundbg.physicsBody?.dynamic = false

Trying to trap the ball inside the circle(roundbg). The problem is that when I use circleOfRadius for my round texture it takes the whole circle and not just the border. I get why circleOfRadius is doing that but can't figure out how to grab just the border. Any ideas? So ideally when ball falls it gets trapped inside the circle(roundbg).

First iOS app/game and very new to this. Thanks for you help!

Upvotes: 4

Views: 1141

Answers (1)

rakeshbs
rakeshbs

Reputation: 24572

SKPhysicsBody(circleOfRadius:) creates a volume based body. In your case you need an Edge based body for the larger circle. Try the following code.

let largeCircleRadius : CGFloat = 100
var largeCirclePath = CGPathCreateMutable();
CGPathAddArc(largeCirclePath, nil, 0.0, 0.0, largeCircleRadius, 0.0, CGFloat(2.0 * M_PI), true)

let largeCircle = SKShapeNode(circleOfRadius: 100)
largeCircle.position = CGPointMake(CGRectGetWidth(frame) / 2.0, CGRectGetHeight(frame) / 2.0)
largeCircle.physicsBody = SKPhysicsBody(edgeLoopFromPath: largeCirclePath)
addChild(largeCircle)

let smallCircle = SKShapeNode(circleOfRadius: 10)
smallCircle.position = CGPointMake(CGRectGetWidth(frame) / 2.0, CGRectGetHeight(frame) / 2.0)
smallCircle.physicsBody = SKPhysicsBody(circleOfRadius: 10)
addChild(smallCircle)

Read more about Edge based and Volume based body here : https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Physics/Physics.html#//apple_ref/doc/uid/TP40013043-CH6-SW3

To create a fraction of a circle, you can change the startAngle and endAngle of the circlePath accordingly. Also use edgeChainFromPath instead of edgeLoopFromPath to not close the loop.

let largeCircleRadius : CGFloat = 100
var largeCirclePath = CGPathCreateMutable();
let startAngle : CGFloat = 3.14
let endAngle : CGFloat = 2 * 3.14

CGPathAddArc(largeCirclePath, nil, 0.0, 0.0, largeCircleRadius, startAngle, endAngle , false)

let largeCircle = SKShapeNode(path: largeCirclePath)
largeCircle.position = CGPointMake(CGRectGetWidth(frame) / 2.0, CGRectGetHeight(frame) / 2.0)
largeCircle.physicsBody = SKPhysicsBody(edgeChainFromPath: largeCirclePath)
addChild(largeCircle)

let smallCircle = SKShapeNode(circleOfRadius: 10)
smallCircle.position = CGPointMake(CGRectGetWidth(frame) / 2.0, CGRectGetHeight(frame) / 2.0)
smallCircle.physicsBody = SKPhysicsBody(circleOfRadius: 10)
addChild(smallCircle)

Upvotes: 6

Related Questions