2012-09-26 28 views
0

我正在使用Java/Slick 2D来玩图形并使用鼠标旋转图像。发生了一些奇怪的事情:图像不一定要面对鼠标。与正常线条成45度角,但距离越远,距离越远。见下面的图片(白色圆圈是鼠标,该文本为角): Image at 80 degrees Image at 45 degrees为什么我的图像偏离中心?

这里是我使用的旋转代码:

int mX = Mouse.getX(); 
     int mY = HEIGHT - Mouse.getY(); 
     int pX = sprite.x; 
     int pY = sprite.y; 
     int tempY, tempX; 
     double mAng, pAng = sprite.angle; 
     double angRotate=0; 

     if(mX!=pX){ 
      mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX)); 
      if(mAng==0 && mX<=pX) 
       mAng=180; 
     } 
     else{ 
      if(mY>pY) 
       mAng=90; 
      else 
       mAng=270; 
     } 

     sprite.angle = mAng; 
     sprite.image.setRotation((float) mAng);  

任何想法是怎么回事?我假设它与图像坐标来自左上角的事实有关,但我不知道如何对付它。 FYI:屏幕640x460,图像128x128,并在窗口居中。

编辑:不幸的是,没有真正的工作。下面是一些更多的信息图片:

Arrow at 35 degrees

EDIT2:找到了答案!不得不改变:INT PX/PY = sprite.x/y以

 int pX = sprite.x+sprite.image.getWidth()/2; 
    int pY = sprite.y+sprite.image.getHeight()/2; 

回答

0

这是我写的一个类似的问题,这可能会帮助一些示例代码。

现在它不使用光滑的,它使用SwingGraphics2D但它可能会帮助你获得一些想法。

public class TestRotatePane extends JPanel { 

    private BufferedImage img; 
    private Point mousePoint; 

    public TestRotatePane() { 

     try { 
      img = ImageIO.read(getClass().getResource("/MT02.png")); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

     addMouseMotionListener(new MouseAdapter() { 

      @Override 
      public void mouseMoved(MouseEvent e) { 

       mousePoint = e.getPoint(); 

       repaint(); 

      } 

     }); 

    } 

    @Override 
    public Dimension getPreferredSize() { 

     return new Dimension(img.getWidth(), img.getHeight()); 

    } 

    @Override 
    protected void paintComponent(Graphics g) { 

     super.paintComponent(g); 

     Graphics2D g2d = (Graphics2D) g.create(); 

     double rotation = 0f; 

     int width = getWidth() - 1; 
     int height = getHeight() - 1; 

     if (mousePoint != null) { 

      int x = width/2; 
      int y = height/2; 

      int deltaX = mousePoint.x - x; 
      int deltaY = mousePoint.y - y; 

      rotation = -Math.atan2(deltaX, deltaY); 

      rotation = Math.toDegrees(rotation) + 180; 

     } 

     int x = (width - img.getWidth())/2; 
     int y = (height - img.getHeight())/2; 

     g2d.rotate(Math.toRadians(rotation), width/2, height/2); 
     g2d.drawImage(img, x, y, this); 

     x = width/2; 
     y = height/2; 
     g2d.setStroke(new BasicStroke(3)); 
     g2d.setColor(Color.RED); 
     g2d.drawLine(x, y, x, y - height/4); 
     g2d.dispose(); 

    } 

} 

enter image description here

你会很明显,需要提供自己的形象;)