我有一个从 A 点移动到随机点 B 的圆圈。当对象靠近 B 点时,会选择一个新的随机目标位置。如果圆平行于 X 轴或 Y 轴移动,则对象将穿过所有的像素并留下实心轨迹。但是如果圆对角移动,它会跳过像素并轻微晃动,使动画不流畅并留下未绘制像素的痕迹。
我的算法是:
- 计算 X 和 Y 距离
- 检查圆圈是否在附近
- 如果是,请选择新目的地
- 如果 2. 为真,则使用毕达哥拉斯定理找到真实距离
- 如果2.为真,计算X和Y速度(坐标的变化)
- 设置新坐标(无论 2. 是否为真)
这是代码:
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);
}
我怀疑问题出在坐标变化的计算上。