我试图让图像跟随我的光标,平滑地移动它所在的位置并转向面对它。
当我靠近原点时,它完美无瑕:图像将完全翻转而没有问题,但是我离窗口原点越远,图像转动越少。当我在屏幕的另一侧时,它不会翻转,而是旋转 5°-15°。
如果有人能指出问题所在,我会很高兴=)
这是我当前的图像代码:
lblRover = new JLabel(sees) { // sees is an ImageIcon
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
double x = getWidth()/2.0;
double y = getHeight()/2.0;
aT.rotate(Math.toRadians(degrees), x, y);
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
lblRover.setSize(179, 180);
lblRover.setLocation(500, 300);
JFrame.getFrames()[0].add(lblRover);
这是处理旋转的代码,加上它的运动:
NewJFrame.PInf = MouseInfo.getPointerInfo();
/* The frame is contained in NewJFrame, PInf is a PointerInfo */
p = (NewJFrame.PInf.getLocation()); // p is a point
p.x-=NewJFrame.getWindows()[0].getLocationOnScreen().x;
p.y-=NewJFrame.getWindows()[0].getLocationOnScreen().y;
//i subtract the location of the window relative to the screen
img = NewJFrame.lblRover.getLocation();
img.x+=NewJFrame.lblRover.getWidth()/2;
img.y+=NewJFrame.lblRover.getHeight()/2;
// img will be the point with the center of my image
sas=getAngle(p,img); // sas is a float variable
NewJFrame.degrees=sas;
//
// From now on i move the image
//
diffx = p.x-img.x;
diffy = p.y-img.y;
diffx/=80; // 80 is an arbitrary number to smooth the effect
diffy/=80; // high numbers will make the image not move at all
Point var = new Point(NewJFrame.lblRover.getLocation());
// I may have to use img here or subtract width and height /2
var.x+=diffx;
var.y+=diffy;
NewJFrame.lblRover.setLocation(var);
// A 5ms sleep to smooth the movement
// I also refresh a debug label
// Also i do refresh the frame, otherwise nothing happens
NewJFrame.jLabel1.setText(""+NewJFrame.lblRover.getLocation().y
+"/"+ p.y+" "+NewJFrame.lblRover.getLocation().x +"/"+ p.x );
NewJFrame.getFrames()[0].repaint();
try {
sleep(5);
} catch (InterruptedException ex) {
Logger.getLogger(thread.class.getName()).log(Level.SEVERE, null, ex);
}