Here's a Java program that makes two balls move around a window.
The task says :
1. If you completed the previous exercise, rebuild the animation so that a collision of the two balls causes both balls to reverse their horizontal and vertical directions.
2. Place a small barrier in the center of the box so that the ball(s) must bounce off the barrier.
I would really appreciate it a lot if anyone would help me, I'm really lost
This is particularly an area of interest for me. Your delay method uses a Thread.sleep() to wait for one clock tick. Here's what the java doc say:
javadoc wrote:Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
This means that a thread can sleep for slightly different intervals depending on systems and is also subject to their underlying load. Your balls can move faster on a faster machine with no load and slower on a machine with high load. If you are designing a game, you would be interested in that.
detecting collision of the two balls need not be complicated. The first, not very accurate, way is to see if the bounding boxes overlap. The second way is, determine the distance between the two centres, and see whether that is larger or smaller than the sum of the radii.
Given the requirement, some strange effects might appear. If ball 1 is coming from the west, ball 2 from the south, and they collide, then the requirement is that ball 1 will go back to the west and ball 2 to the south, not what you would expect.
To counter the effect that Salvin mentions: a remedy is to measure the elapsed time between two invocations, and if that is (much) larger than 20 ms adjust the time units. However, that complicates matters, so I wouldn't tackle that unless it turns out to be a problem (but I do not expect that).
I think there are two approaches for the timer delay that I can think of. Both of them involves simply recording the lastExecutedTime. Whenever you do your tick, simply update the lastExecutedTime and also calculate the diff in milliseconds from the last run time. This number is the basis of your calculation :
Cycle/Tick based logic:
Let's assume your "cycle" is 10ms and the difference between last and now is 15ms, then you have to account for 1.5 cycles in your current render. e.g if your ball moves 1 unit every cycle, it should move 1.5 unit this cycle.
Time based logic:
Alternatively, you can work your logic based on time. i.e. decide how much the ball should move given that 15ms has passed. e.g. if your ball moves 1 unit every 10ms, then it should move 1.5 unit for 15ms.