Dalibor - 1 year ago 127
Swift Question

# How to apply a SKPhysicsBody to a bezier curve?

I'm creating a motocross game where I have a curved ground on which the player should drive. My code for creating the ground looks like this:

``````    let path = UIBezierPath()
let startPoint = CGPoint(x: 0.0, y: self.playerCamera.position.x + 50)
let endPoint = CGPoint(x: self.frame.width, y: self.playerCamera.position.x + 50)

path.moveToPoint(startPoint)
path.addCurveToPoint(endPoint, controlPoint1: CGPoint(x: 200.0, y: 100), controlPoint2: CGPoint(x: 400.0, y: -100))

let myShape = SKShapeNode()
myShape.path = path.CGPath
myShape.lineWidth = 20

myShape.physicsBody = SKPhysicsBody(edgeLoopFromPath: path.CGPath)

myShape.physicsBody?.dynamic = false
myShape.physicsBody?.affectedByGravity = false
myShape.physicsBody?.allowsRotation = false

``````

My problem is that the player drives on the curve as if it would be a rectangle instead of following the curve.

How can I apply the actual curve or path as the PhyicsBody?

SOLUTION:

I think it is impossible to do it without the assistance of a tool.

Please have a look at this: http://avionicsdev.esy.es/article.php?id=13&page=1

TOOL:

You can use this tool to achieve the desired effect:

http://insyncapp.net/SKPhysicsBodyPathGenerator.html

"This tool will let us draw a path and then returns code that will help us draw that path into Xcode" (excerpt from the first link)

METHODOLOGY:

You may have to screen cap your UIBezierPath and convert it to a Sprite, but I am not certain it is necessary. Have a look at the explanations of the tool.

SOLUTION 2:

Change Game Engine.

In my opinion, you might be able to find a way to achieve what you want, but it won't be a simple and straightforward solution. On the other hand, other game engines are more complete and should provide you all you need without having to use "tricks" to achieve what you want.

I hope I am wrong and SpriteKit is indeed more complete than that, but it doesn't look like it.