通过 atan2 方法旋转对象时出现问题

Issue when rotating an object through the atan2 method

我正在尝试让图像跟随我的光标,平滑地移动到它所在的位置并转向它。

当我靠近原点时,它可以完美地工作:图像将完全翻转而不会出现问题,但是我离 window 的原点越远,图像转动的越少。当我在屏幕的另一边时,它不会翻转而是旋转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);
        }

好吧,经过多次尝试,我缩小了范围。

现在,旋转代码放在最后,重绘之前,看起来像这样:

sas=this.getAngle((float)diffy,(float)diffx);
NewJFrame.degrees=sas;

我还创建了这个使用两个浮点数而不是两个点数的新方法:

public float getAngle(Float x, Float y) {
float angle = (float) Math.toDegrees(Math.atan2(x, y));
//System.out.println(angle);
return angle;

我不知道为什么它现在可以工作,但以前没有,因为过程基本上是相同的...但是它可以工作! =D