Hadi
Hadi

Reputation: 209

Restricting a node within another in SpriteKit

I'm new to SpriteKit, trying to build basic Breakout game. The problem I'm facing is that I can't restrict the paddle within the screen (that's yet another node with blue texture as shown in image). When I move the paddle it goes beyond the screen limits. I've applied physics to both, screen area and the paddle but no luck.enter image description here

Upvotes: 0

Views: 355

Answers (1)

0x141E
0x141E

Reputation: 12753

Your paddle doesn't collide appropriately with the edge because you are moving it by changing its position directly. To participate in the physics simulation, the paddle must be moved by setting its velocity or by applying a force or impulse to its physics body. For example,

for touch in (touches as! Set<UITouch>) {
    let location = touch.locationInNode(self)
    if (location.x < size.width/2.0) {
        paddle.physicsBody?.applyImpulse(CGVectorMake(-scale, 0))
    }
    else {
        paddle.physicsBody?.applyImpulse(CGVectorMake(scale, 0))
    }
}

where scale determines the amount of momentum that is applied to the body in the x dimension.

EDIT:

Alternatively, you can constrain the paddle's x position to be within a set range by

let range = SKRange(lowerLimit: CGRectGetMinX(view.frame), upperLimit: CGRectGetMaxX(view.frame))
let constraint = SKConstraint.positionX(range)
paddle.constraints = [constraint]

Add the above to the didMoveToView method.

Upvotes: 1

Related Questions