Search code examples
objective-cxcodeswiftsprite-kitskphysicsbody

sprite kit swift boundary for the scene


this is a objective-c code that work exactly for physics body collision around the screen

    self.physicsWorld.gravity = CGVectorMake(10.0f, -10.0f);
    //  Create a physics body  borders the screen
    SKPhysicsBody* borderBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    //  Set physicsBody of scene to borderBody
    self.physicsBody = borderBody;

    SKSpriteNode* aa = [SKSpriteNode spriteNodeWithImageNamed:@"ca1.png"];
    aa.position = CGPointMake(20, 20);
    aa.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:aa.frame.size.width/2];

    aa.physicsBody.friction = 0.0f;
    aa.physicsBody.restitution = 1.0f;
    aa.physicsBody.linearDamping = 0.0f;

    [self addChild:aa];

that should be the equivalent for swift

self.physicsWorld.gravity = CGVectorMake(CGFloat(10.0), CGFloat(-10.0));
let physicsBody = SKPhysicsBody (edgeLoopFromRect: self.frame)
self.physicsBody = physicsBody

var sp=SKSpriteNode()
var atexture=SKTexture(imageNamed: "candycane.png")
sp=SKSpriteNode(texture: atexture)
sp.position=CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))

     sp.physicsBody = SKPhysicsBody(circleOfRadius:  bird.size.height / 2)
    sp.physicsBody?.friction = 0
    sp.physicsBody?.restitution = 1
    sp.physicsBody?.linearDamping = 0

    self.addChild(sp)

but work only for top and bottom the spritenode can go out the left and right

what is the problem ?. how i can have a boundary for the scene in swift ?.


Solution

  • so this is the magic trick

    lets add this in GameViewController

    let scene = GameScene(size: skView.bounds.size)
    

    end get the same result of the objective-c all work fine