2012-08-11 87 views
1

到目前为止,我有一个Java应用程序,我画了一个圆圈(玩家),然后在顶部(枪管)上绘制一个绿色的矩形。我拥有它,所以当玩家移动时,枪管就跟着它。我希望它找到鼠标指向的位置,然后相应地旋转桶。举个例子,我的意思是看这个视频,我发现http://www.youtube.com/watch?v=8W7WSkQq5SU看看当他移动鼠标时播放器图像如何反应?爪哇2d旋转方向鼠标点

这里是什么样的游戏看起来就像到目前为止的图像:

My Progress

那么,如何将其旋转这样吗?顺便说一句,我不喜欢使用affinetransform或Graphics2D旋转。我希望有更好的方法。由于

+0

*顺便说一句,我不喜欢使用的AffineTransform或Graphics2D的旋转*好运然后:P - 在即将做你想要与效率的任何级别什么的唯一方式就是java通过'Affinetransform'或'Graphics2D.rotate',除非你想“手动”调整pix埃尔斯你自己,然后我几乎认为符合*更好的方式*标准 – MadProgrammer 2012-08-11 02:22:12

回答

9

使用Graphics2D旋转方法确实是最简单的方法。这里有一个简单的实现:

int centerX = width/2; 
int centerY = height/2; 
double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI/2; 

((Graphics2D)g).rotate(angle, centerX, centerY); 

g.fillRect(...); // draw your rectangle 

如果你想,当你这样做,你可以继续正常绘图,使用去除旋转:

Graphics2D g2d = (Graphics2D)g; 
AffineTransform transform = g2d.getTransform(); 

g2d.rotate(angle, centerX, centerY); 

g2d.fillRect(...); // draw your rectangle 

g2d.setTransform(transform); 

这是只使用Graphics2D一个好主意,无论如何,抗锯齿等

+0

+1好的和简单 – MadProgrammer 2012-08-11 15:43:19

+0

真棒,谢谢你的简单的代码!不知道那是更简单的哇! – 36redsoxfan 2012-08-13 20:42:42

2

使用AffineTransform,对不起,只有这样,我知道如何:P

public class RotatePane extends javax.swing.JPanel { 

    private BufferedImage img; 
    private Point mousePoint; 

    /** 
    * Creates new form RotatePane 
    */ 
    public RotatePane() { 

     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(); 

    } 
} 

会产生这种效果

Rotating

红线(从中心指出)将要按照光标。