2012-08-11 86 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

紅線(從中心指出)將要按照光標。