ポイント A からランダムなポイント B に移動する円があります。オブジェクトがポイント B に近づくと、新しいランダムなターゲット位置が選択されます。円が X 軸または Y 軸に平行に移動している場合、オブジェクトは途中ですべてのピクセルを通過し、実線を残します。ただし、円が斜めに移動すると、ピクセルがスキップされてわずかに揺れるため、アニメーションが滑らかにならず、ペイントされていないピクセルの跡が残ります。
私のアルゴリズムは次のとおりです。
- X と Y の距離を計算する
- 円が近くにあるかどうかを確認する
- その場合は、新しい目的地を選択してください
- 2.が真の場合、ピタゴラスの定理を使用して実際の距離を見つけます
- 2. が true の場合、X と Y の速度 (座標の変化) を計算します。
- 新しい座標を設定します(2.がtrueかどうかに関係なく)
コードは次のとおりです。
public void move ()//движение
{
//finds the X and Y distance to the destination
int triangleX = nextLocationX - coorX;
int triangleY = nextLocationY - coorY;
//if too near the coordinates of the destination changes
if (Math.abs(triangleX) <= Math.abs(speedX) || Math.abs(triangleY) <= Math.abs(speedY))//setting the new target
{
//setting the new destinatio
int randInt;
for (;;)//I don't want the the new destination to be that same spot
{
randInt= randGen.nextInt(appletX);
if (randInt != nextLocationX)
{
nextLocationX = randInt + radius;
break;
}
}
for (;;)
{
randInt = randGen.nextInt(appletY);
if (randInt != nextLocationY)
{
nextLocationY = randInt + radius;
break;
}
}
//calculating the change of the circle's X and Y coordinates
triangleX = nextLocationX - coorX;
triangleY = nextLocationY - coorY;
speedX = ((double)(speed * triangleX) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
speedY = ((double)(speed * triangleY) / (Math.sqrt (Math.pow(triangleX, 2) + Math.pow(triangleY, 2))));
}
//the realCoor variables are from type double
//they are the exact coordinates of the circle
//If I only use integers, the circle almost
//never reaches it's destination
//unless the change of the coordinates gets calculated
//after every time they change
realCoorX = realCoorX + speedX;
realCoorY = realCoorY + speedY;
coorX = (int)Math.round(realCoorX);
coorY = (int)Math.round(realCoorY);
}
問題は座標の変化の計算にあると思われます。