Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop SKSpriteNode from leaving view (Swift)

Hello i want to prevent a SKSpriteNode from leaving the screen or to make the Node bounce back when it hits the border of the screen. And is it also possible to call a function when its hits the border?

If found this question Click

Where he uses this code:

let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = borderBody
borderBody.friction = 0.0
borderBody.restitution = 1.0

But for some reason it only block my Node (which is dynamic) from moving out of the the top and bottem, but It's able to move out of the side.

(Keep in mind that im new to SpriteKit and Swift)

EDIT: i found this code:

extension GameScene: SKPhysicsContactDelegate {
    func didBeginContact(contact: SKPhysicsContact!) {
        let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch (contactMask) {
        case BodyType.pipe.toRaw() |  BodyType.bomb.toRaw():
            println("Contact with a bomb")
            if contact.bodyA.categoryBitMask == BodyType.pipe.toRaw() {
                explode(pipe: contact.bodyA.node as SKSpriteNode)
            } else {
                explode(pipe: contact.bodyB.node as SKSpriteNode)
            }
        case BodyType.pipe.toRaw() |  BodyType.bird.toRaw():
            println("Contact with a pipe")
            bird.pushDown()
        case BodyType.ground.toRaw() | BodyType.bird.toRaw():
            println("Contact with ground")
            for actor in actors {
                actor.stop()
            }

            let shakeAction = SKAction.shake(0.1, amplitudeX: 20)
            screenNode.runAction(shakeAction)
        default:
            return
        }

    }

I read it was something like setting categories? Is this code anygood?

like image 756
Egghead Avatar asked Oct 21 '22 00:10

Egghead


1 Answers

Set the physics body to the size of the screen

self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
like image 86
Cyril Avatar answered Nov 04 '22 01:11

Cyril