0
votes

I'm trying to build a game, using SpriteKit, in which there's a ball that bounces up and down. Now I want to let the player control the balls movement in the X axis and let the physics engine control the Y velocity.

For example, when the ball hits a corner it starts moving sideways on it's own. I would like it to bounce of the corner and then quickly stabilize and stop moving side-ways. Is there anyway of doing this without trying to counteract any sideways movement by applying an impulse? Would it be easier to just manually control the ball's movement up and down?

I've tried applying a counteracting force without much success (the ball freaks out):

  override func update(currentTime: NSTimeInterval) {
    let ballDx = ball?.physicsBody?.velocity.dx
    if let ballVelocityX = ballDx  {
      if ballVelocityX != 0 {
        ball?.physicsBody?.applyForce(CGVectorMake(ballVelocityX * -1, 0))
      }
    }
  }
1

1 Answers

1
votes

Sounds like you need to apply linear damping in the x direction. Here's an example of how to do that:

// Adjust this value as needed. It should be in [0,1], where a value of 1 will
// have no effect on the ball and a value of 0 will stop the ball immediately.
let xAlpha:CGFloat = 0.95

override func update(currentTime: CFTimeInterval) {
    /* Apply damping only in x */
    let dx = sprite.physicsBody!.velocity.dx * xAlpha
    let dy = sprite.physicsBody!.velocity.dy
    sprite.physicsBody?.velocity = CGVectorMake(dx, dy)        
}