Stop SKSpriteNode from viewing (Swift)

Hello, I want to prevent SKSpriteNode from leaving the screen or returning Node when it hits the border of the screen. And also can the function be called when it hits the border?

If you found this question Click

Where does he use this code:

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


But for some reason, it blocks my Node (which is dynamic) from moving out of the top and the top, but it is able to move from the side.

(Please be aware that im new for 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")
        case BodyType.ground.toRaw() | BodyType.bird.toRaw():
            println("Contact with ground")
            for actor in actors {

            let shakeAction = SKAction.shake(0.1, amplitudeX: 20)



I read that it was something like category settings? Is this code invalid?


source to share

2 answers

Set physical body to screen size

self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)




Yes it is possible.

  • You need to set up a SKNode with a physical body of type rect and give it the size self.size. This will create a physical body for the screen borders.

  • Then you have to adjust the bit mask category on the physical body above the SKNode. This is a way to identify our physical body.

  • And then you have to give the above SKNode a collision bitmask equal to the category of the Node library bit you don't want to be left on screen. This will crash Node at the border and fall back.

  • Finally, if you set the contact bitmask or in the bitmask category another. The apple function "didBeginContact" will run, and there you can do something.

Hope it helps!



All Articles