SpriteKit physics in Swift – Ball slides against wall instead of reflecting

This appears to be an issue with collision detection. Most have found solutions by using the didBeginContact and reapplying the force at an opposite direction. Note he says didMoveToView but corrects himself in a later comment to didBeginContact.

See comments at the bottom of the Ray Wenderlich tutorial here

I have a fix for the problem with the ball “riding the rail” if it
strikes at a shallow angle (@aziz76 and @colinf). I added another
category, “BorderCategory” and assigned it to the border PhysicsBody
we create in didMoveToView.

and a similar SO question here explaining why it is happening.

Even if you do that, though, many physics engines (including
SpriteKit’s) have trouble with situations like this because of
floating point rounding errors. I’ve found that when I want a body to
keep a constant speed after a collision, it’s best to force it to —
use a didEndContact: or didSimulatePhysics handler to reset the moving
body’s velocity so it’s going the same speed it was before the
collision (but in the opposite direction).

Also another thing I noticed is you are using a square instead of a circle for your ball and you may want to consider using…

ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)

So turns out you aren’t crazy which is always good to hear from someone else and hopefully this will help you find a solution that works best for your application.

Leave a Comment