How to use the SpriteKit method body(at : CGPoint)?

Viewed 153

I have game that during the game your finger moves around and should avoid hitting some obstacles. I know how to use collision but I recently heard that there is a funtion called the body(at : point). I should say that I have masked my obstacles. Because of that I can't use the contains(point) function. I really want to use the body(at : point) function otherwise I know how to work with collisions.

Some of my code:

play_button = self.childNode(withName: "play_button") as! SKSpriteNode
for t in touches{
    let fingerlocation = t.location(in: self)
    if physicsworld.body(at : fingerlocation)
    {
        let so = level6(fileNamed:"level6")
        so?.scaleMode = .aspectFill
        self.view?.presentScene(so!, transition: 
        SKTransition.crossFade(withDuration: 1))
    }
}

but it does not work.

2 Answers

I've had a similar problem, "if let body = physicsWorld.body(at: touchLocation){...}" was responding wherever I've touched the screen.

I figured out, that by default the SKScene object created its own SKPhysicsBody which was set on top of all other SKPhysicsBodies. I solved this problem by making a new SKPhysicsBody for the scene, which didn't interfere anymore. Hope this code will help you.

inside of didMove:

let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
Related