I am pretty new in programming and got the task to create a kind of a billard game. Now I have the problem that sometimes the ball did not rebound from the wall.
You have two variables per dimension: xDirection and xSpeed for example. However you do not need two variables. One is enough. The sign of the variable defines direction. The magnitude, or abs(value) defines the effective value in that dimension along a direction. If you split the magnitude from direction, you are creating more work for yourself. You don't have to. I believe thinks will be more clear if you check the example.
I store mouseX, mouseY and pmouseX and pmouseY, because if the mouse is released the two last position are saved in those variables. With the stored values I can find out the last direction the ball made. I know it could be written easier, but my tries with the original variables failed.
Answers
in my opinion, this
yDirection = -yDirection;
can lead to stuttering near the screen border in that it can just go back and forth between a negative and a positive value.
To avoid stuttering better say
yDirection = - abs(yDirection); // always negative
OR
yDirection = abs(yDirection); // always positive
I have implemented your suggested improvement.
The ball rebound seems to work except the ball hits the upper border first.
excuse me, is the -abs and the abs section the other way round in line 4 and 8 ?
when it's
xPosition < diameter/2
we wantxDirection = abs(xDirection);
when it's
xPosition > width-diameter/2
we wantxDirection = - abs(xDirection);
here
Tried to change the minus and plus, but did not solve the problem. :(( :(( :((
You need to study this example: https://processing.org/examples/bounce.html
You have two variables per dimension: xDirection and xSpeed for example. However you do not need two variables. One is enough. The sign of the variable defines direction. The magnitude, or abs(value) defines the effective value in that dimension along a direction. If you split the magnitude from direction, you are creating more work for yourself. You don't have to. I believe thinks will be more clear if you check the example.
Kf
Changed the collision detection according to the example and found out that everything seems to work fine, if I don't calculate the wall absorption.
It's not good to call setup really
Instead make a new function init() and call this
Basically move all from setup into init except for size
I don't see why you store mouseX, mouseY and pmouseX and pmouseY! just work with original variables mouseX etc.
You are throwing the ball with the mouse, right? I think that can be written easier when you say mouseX - pmouseX ---- but make a copy first.......
I store mouseX, mouseY and pmouseX and pmouseY, because if the mouse is released the two last position are saved in those variables. With the stored values I can find out the last direction the ball made. I know it could be written easier, but my tries with the original variables failed.
I see