I tried Collision Simulation of a point and a line. The point move by adding 1 to point.x and point.y infinitely. At once, The main thread checks collision two objects. If the point collides to the line, it stops. It works very well, but happens some error. If main thread loops without delay, the result of checking method always returned 'False'(In case that should return 'True' absolutely). There was no error in the following some cases.
- Add small delay in main thread. (For example, add some code likes "System.out.println() or "Thread.sleep(1)")
- Change the collision checking method to 'synchronized'.
Why does this happen?
[Main Thread]
public static void main(String[] args) throws IOException {
DrawingFrame d = new DrawingFrame();
PointObject p = new PointObject(200,200);
LineObject l = new LineObject(100,10,new Vector(500,Math.toRadians(60.0f)));
p.move();
d.addDrawable(p);
d.addDrawable(l);
while(true) {
// if main thread loops infinitely without delay,
// the result of checking method always returned 'False'.
// System.out.println(); <-- DELAY
if(l.isAbove(p)) p.stop=true;
}
}
[Move]
public void move() {
new Thread(new Runnable() {
@Override
public void run() {
while(!stop) {
x++;
y++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
[Check]
@Override
public boolean isAbove(PointObject p) {
return Math.abs(p.y-(Math.tan(this.vector.radian)*(p.x-this.x)+this.y))<=ERROR;
}