Nat
Nat

Reputation: 12948

Node should bounce when hitting scene edges

I'm starting with SpriteKit. I want my spriteNote to bounce from the edges of the device. The problem is that I don't see any method, which would allow me to add edges.

// initWithSize:
_player.physicsBody.dynamic = YES;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    self.physicsWorld.gravity = CGVectorMake(0.0f, 1.0f);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    self.physicsWorld.gravity = CGVectorMake(0.0f, -1.0f);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    self.physicsWorld.gravity = CGVectorMake(0.0f, -1.0f);
}

I've tried to add something to update method, however the location looks strange (I have landscape mode only, _player.position.y is ~ 150px when I already don't see the player @.@ player graphic is 50x50px, node is SKPhysicsBody bodyWithCircleOfRadius:sprite.size.width / 2).

Upvotes: 0

Views: 89

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

In order to add an edge around the screen for collisions in SpriteKit, you will need to attach a physicsBody to the scene.

In the -initWithSize: method, you need to add the following line:

self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

This will add a boundary around the scene which the balls can bounce off.

Upvotes: 1

Related Questions