NSSwift
NSSwift

Reputation: 395

How to prevent part of SKSpriteNode from passing Edge

I created a left edge in the following way:

let leftBorderEdgeRect = CGRectMake(self.frame.origin.x, self.frame.origin.y, 0.5 , CGRectGetHeight(frame))
let leftBorderEdge = SKNode()
leftBorderEdge.physicsBody = SKPhysicsBody(edgeLoopFromRect: leftBorderEdgeRect)

Any time one SKSpriteNode gets into contact with the edge about 10% of it's size (width) passes the edge. I am moving the sprite by applying forces. For now I pause the scene when contact is established within didBeginContact in the following way:

if firstBody.categoryBitMask == spriteCategory && secondBody.categoryBitMask == leftBorderCategory  {
    print("contact with leftBorder")
    print("firstBody.node xPos: \(firstBody.node?.position.x) and yPos: \(firstBody.node?.position.y)")
    self.view?.paused = true
}

I am not really sure what's causing it to pass the edge border. I also tried setting a world edge for the whole scene but still got the same result. I am using the default anchor point for my sprite.

Upvotes: 0

Views: 109

Answers (1)

Alain T.
Alain T.

Reputation: 42143

Have you tried setting usesPreciseCollisionDetection to true ?

if you object if small, or moving very fast or you have low frame rate, the distance the object moves between frames may be greater than a few pixels. This means that by the time the next collision detection is evaluated, the unit's movement may have already taken it beyond the edge.

If you have a small number of moving objects and merely want to constrain movement on the basis of the bounds of the scene's rectangle, you could override the update() method of your SKScene and check boundaries there. Checking for a point in or out of a rectangle is quick enough that it won't affect the game performance if you're only checking a few sprites.

Upvotes: 0

Related Questions