So i'm just trying to make a ball bounce around the screen which should slow down due to gravity and reflect (bounce) from the wall like a normal ball would. Can someone give some basics and VERY simple implementation of this? Other examples seem a bit "overdone" and seem to go beyond what I want to do. I've tried this:
public void updateLogic() {
if (x < -1) {
xPos += (-x * gravity);
} else if (x > 1) {
xPos -= (x * gravity);
}
if (y > 1) {
yPos += (y * gravity);
} else if (y < -1) {
yPos -= (-y * gravity);
}
}
This is the closest I got by myself. By the way the x and y values are from the accelerometer. Any help would be much appreciated, thanks!
I think you'll need 3 things for this, forces (x and y, which you have), velocities (call them xVel and yVel) and positions (xPos and yPos which you also have). The position of the ball is updated (in the simplest way) by:
xPos += dt*xVel;
yPos += dt*yVel;
xVel += dt*x;
yVel += dt*y;
The variable 'dt' is the timestep, which controls how fast the ball will move. If this is set too large, though, the program will be unstable! Try dt = 0.001 or so to start and gradually set it higher.
Then, to get the ball to reflect from the walls, just flip the velocity if it hits a 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. The 'xPos = ...' is just to stop the ball going off the edge of the screen. If you'd like the ball to bounce a little less every time it hits a wall, change the '-1.0' to '-0.9' or something (this is the coefficient of restitution).
Hopefully that should be all. Good luck!
Some comments on your actual code:
Both of these lines do exactly the same thing:
yPos -= (-y * gravity);
yPos += (y * gravity);
likewise, both of these lines do the same thing:
xPos += (-x * gravity);
xPos -= (x * gravity);
You are not handling the cases -1 <= x <= 1
or -1 <= y <= 1
Some comments on the concepts:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With