Search code examples
swiftxcodesprite-kitgame-physics

SpriteKit - Bouncing node constant speed/velocity?


enter image description here

Simple setup - I have bouncing ball nodes (blue) and static ball nodes (green). The grey box has Physics body SKPhysicsBody(edgeLoopFrom: box.frame), so it limits the bouncing ball from moving outside. I set the bouncing balls node (blue) velocity to a random CGVector upon creation and it starts moving. It bounces off the static ball node (green), and off the edges of the grey box.

My general SKPhysicsBody setup with all nodes is:

node.physicsBody?.restitution = 1
node.physicsBody?.friction = 0.0
node.physicsBody?.linearDamping = 0.0
node.physicsBody?.angularDamping = 0.0

My question is: How do I make sure the bouncing ball does move at a constant speed? After a couple of bounces, the node is either speeding up, or slowing down.


Solution

  • In order to achieve this, I normalized the vector whenever the physics engine detects a collision. So in func didBegin(_ contact: SKPhysicsContact), the following happens:

    let length = hypotf(Float(node.velocity.dx), Float(node.velocity.dy)) 
    let multiplier = (290.0 / length)
    firstBody.velocity.dx *= CGFloat(multiplier)
    firstBody.velocity.dy *= CGFloat(multiplier)
    

    290.0 is an arbitrary value that determines the speed of ball.

    For reference, check this answer.