我正在尝试在对象保持动画的同时在鼠标点击上移动对象。这个网站上有一些类似的帖子,我的代码基于这个答案:
An efficient algorithm to move ostrichs along a line at a constant speed
但是我想使用一个线程来保持对象的动画效果。我该怎么做?这是我的代码:
public void movePlayer(Graphics g, int finalX, int finalY)
{
int length = finalX - xpos;
int height = finalY - ypos;
int oldXpos = xpos;
int oldYpos = ypos;
double speed = 20;
double distanceX = (length)/speed;
double distanceY = (height)/speed;
double distance = (Math.hypot(length,height));
double distanceTraveled = 0;
//This currently doesn't work:
move = new Thread(this);
{
while (distanceTraveled<distance)
{
//move the object by increments
xpos += distanceX;
ypos += distanceY;
distanceTraveled = Math.hypot(xpos-oldXpos, ypos - oldYpos);
drawPlayer(img, g);
for(int x = 0; x < 100000; x ++);
}
}
}
答案 0 :(得分:1)
如果这是Swing,为什么不简单地使用MouseListener来帮助你拖动对象?如果要与鼠标分开动画,除非要冻结事件线程,否则不要使用while(true)
循环。请改用Swing Timer。如果这不是Swing,请告诉我们更多细节(拍摄,无论如何都要这样做)!