I think for this you will need three things: strength (x and y, which you have), speed (name them xVel and yVel) and position (xPos and yPos, which you also have). The ball position is updated (in the easiest way):
xPos += dt*xVel; yPos += dt*yVel; xVel += dt*x; yVel += dt*y;
The 'dt' variable is a timestep that determines how fast the ball will move. If this is too large, the program will be unstable! Try dt = 0.001 or so to start and gradually set it higher.
Then, to make the ball bounce off the walls, simply flip the speed if it hits the wall:
if (xPos > xMax) { xPos = xMax; xVel *= -1.0; } else if (xPos < 0.0) { xPos = 0.0; xVel *= -1.0; }
and the same for y. "XPos = ..." is just stopping the ball going from the edge of the screen. If you want the ball to bounce a little less each time it hits the wall, change the value of โ-1.0โ to โ-0.9โ or something like that (this is a restitution coefficient ).
Hope this should be all. Good luck
source share