Ball bouncing off the wall doesn't work

2019-06-05 06:23发布

问题:

I am trying to let the ball bounce back when it is about to go off the screen.

I thought it should work with this:

 bal.physicsBody?.velocity.dx = -bal.physicsBody?.velocity.dx

but it doesn't..

I am getting this error: Could not find an overload for "-" that accepts the suplied arguments.

How to solve this?

回答1:

You could do either:

if let physicsBody = bal.physicsBody {
    physicsBody.velocity.dx *= -1
}

Or

bal.physicsBody?.velocity.dx *= -1

Or, if you're absolutely certain bal has a physics body you could force-unwrap, with either of the following methods:

bal.physicsBody!.velocity.dx *= -1
bal.physicsBody!.velocity.dx = -bal.physicsBody!.velocity.dx