Im trying to create a timed event in java.swing which when fired moves a dot, or ball from point A to point B. I�ve tried the mathematical way i.e every 20 milliseconds or so the point changes position like this:
currentX += abX / (Math.abs(abX)); // Where abX is the distance from X of currentY += abY / (Math.abs(abX)); // point A to x of point B and abY is the // distance from Y of point A to Y of point B
A simple geometry...but the screen is made up of pixels and there is no such thing as 1/2 pixel or 1/3 pixel as the calculation of abY / (Math.abs(abX)) often result there for the dot always miss its target i.e point B on longer ranges.
I need an invisible line to be drawn between A and B and the dot to follow it. Please help.
Joined: Jan 29, 2003
When you compute the new position from the prior position over and over you add up errors. So if it goes a pixel north once and a pixel north again you're off by two. Maybe you could compute the new position from the original position and the number of steps you have taken.
currentX = originalX + ( stepSizeX * stepCount )
That will get you very close to the end with only one error in the last calculation instead of a sum of many errors.
And if you have to hit the targe precisely, you might work backwards.
Or you might try keeping current position at high precision and rounding to the nearest pixel when you draw. I guess you could use floating point or do all your math with values multiplied by a million and divide by a million as you draw.
Any way you do it you might see some jiggle around your invisible line as you go.
Any of those sound like they might work?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Apr 30, 2005
Yes it did help alot i.e by incrementing a variable by abY/Math.abs(abX) every time and adding it to the original Y.