2016-04-29 107 views
-1

我有3天的时间寻找以螺旋方式在物体上移动,但我想我必须寻找在弧上移动物体的问题的一小部分。 看到我的问题:https://stackoverflow.com/questions/36917560/moving-rectangle-spiral-animation-java?noredirect=1#comment61428911_36917560沿着带有java图形的弧形路径移动物体

现在,问题是我如何计算弧上存在的点。这是我的方法来获得新的X和Y点(算法不代码)

1-绘制弧形在Java中使用这种方法 g2d.fillArc(start_point_X_Arc,start_point_Y_Arc,width_of_arc,height_of_arc,start_angle,end_angle);

2-在相同的Start_point_X,Start_point_Y上绘制对象。在这里,我将使用这种方法绘制一个矩形

g2d.drawRect(start_point_X_Rect,Start_point_Y_Rect,10,10);

3-因为我使用一个计时器,它需要一个ActionListener actionPerformed方法将更新Start_point_X,Start_point_Y的值的矩形

与这里的问题是我不能计算新X,Y值的值将会做问题的移动部分(我知道这些词不是专业词汇)。

正因为如此我寻找如何计算电弧点,我发现对于圆形

X = center_X +半径* COS(角度)

Y = center_y +半径参数方程* sin(角度)

我知道这些公式可能会用来获得新的积分,但我不擅长数学。

因此,我需要帮助做对象在弧形路径中移动,我认为这将帮助我做一个物体在螺旋路径中移动。如果我的算法错误或任何错误,请给我建议,以简单的方式做到这一点。

这是一个代码,我让它绘制一个圆弧&矩形,矩形在对角线路径上移动。

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.RenderingHints; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.geom.AffineTransform; 
import java.awt.geom.Arc2D; 
import java.awt.geom.Path2D; 
import java.awt.geom.PathIterator; 
import java.awt.geom.Point2D; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Test { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public class SpiralPath extends Path2D.Double { 

     public SpiralPath(int size) { 
      int numIterations = 5; 
      int arcGrowDelta = (size/numIterations)/2; 
      int arcWidth = 0; 

      int centerX = size/2; 
      int centerY = size/2; 
      moveTo(centerX, centerY); 

      for (int i = 0; i < numIterations; i++) { 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth, 2 * arcWidth, 180, 180, Arc2D.OPEN), true); 
       arcWidth += arcGrowDelta; 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth - arcGrowDelta, 2 * arcWidth, 0, 180, Arc2D.OPEN), true); 
      } 
     } 

    } 

    public class SpiralPath2 extends Path2D.Double { 

     public SpiralPath2(int size) { 
      int numIterations = 5; 
      int arcGrowDelta = (size/numIterations)/2; 
      int arcWidth = 0; 

      int centerX = size/2+200; 
      int centerY = size/2; 
      moveTo(centerX, centerY); 

      for (int i = 0; i < numIterations; i++) { 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth, 2 * arcWidth, 180, 180, Arc2D.OPEN), true); 
       arcWidth += arcGrowDelta; 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth - arcGrowDelta, 2 * arcWidth, 0, 180, Arc2D.OPEN), true); 
      } 
     } 

    } 

    public Test() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private SpiralPath spiralPath; 
     private final Rectangle box; 

     private List<Point2D> points; 
     private double angle; 
     private Point2D pos; 
     private int index; 

     private SpiralPath2 spiralPath2; 
     private final Rectangle box2; 

     private List<Point2D> points2; 
     private double angle2; 
     private Point2D pos2; 
     private int index2; 

     protected static final double PLAY_TIME = 5000; // 5 seconds... 

     private Long startTime; 

     public TestPane() { 
      spiralPath = new SpiralPath(150); 
      box = new Rectangle(0, 0, 10, 10); 

      points = new ArrayList<>(25); 
      PathIterator pi = spiralPath.getPathIterator(null, 0.01); 
      while (!pi.isDone()) { 
       double[] coords = new double[6]; 
       switch (pi.currentSegment(coords)) { 
        case PathIterator.SEG_MOVETO: 
        case PathIterator.SEG_LINETO: 
         points.add(new Point2D.Double(coords[0], coords[1])); 
         break; 
       } 
       pi.next(); 
      } 

      spiralPath2 = new SpiralPath2(200); 
      box2 = new Rectangle(0, 0, 10, 10); 

      points2 = new ArrayList<>(25); 
      PathIterator pi2 = spiralPath2.getPathIterator(null, 0.01); 
      while (!pi2.isDone()) { 
       double[] coords = new double[6]; 
       switch (pi2.currentSegment(coords)) { 
        case PathIterator.SEG_MOVETO: 
        case PathIterator.SEG_LINETO: 
         points2.add(new Point2D.Double(coords[0], coords[1])); 
         break; 
       } 
       pi2.next(); 
      } 

      pos = points.get(0); 
      pos2 = points2.get(0); 
      Timer timer = new Timer(40, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 

        if (startTime == null) { 
         startTime = System.currentTimeMillis(); 
        } 
        long playTime = System.currentTimeMillis() - startTime; 
        double progress = playTime/PLAY_TIME; 
        if (progress >= 1.0) { 
         progress = 1d; 
         ((Timer) e.getSource()).stop(); 
        } 

        int index = Math.min(Math.max(0, (int) (points.size() * progress)), points.size() - 1); 
        int index2 = Math.min(Math.max(0, (int) (points2.size() * progress)), points2.size() - 1); 

        pos = points.get(index); 
        pos2 = points2.get(index2); 
        if (index < points.size() - 1) { 
         angle = angleTo(pos, points.get(index + 1)); 
        } 

        if (index2 < points2.size() - 1) { 
         angle2 = angleTo(pos2, points2.get(index + 1)); 
        } 
        repaint(); 
       } 
      }); 

      timer.start(); 
     } 

     protected double angleTo(Point2D from, Point2D to) { 
      double angle = Math.atan2(to.getY() - from.getY(), to.getX() - from.getX()); 
      return angle; 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(500, 400); 
     } 

     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      applyQualityRenderingHints(g2d); 

      g2d.translate(20, 50); 
      g2d.draw(spiralPath); 
      g2d.draw(spiralPath2); 
      AffineTransform at = new AffineTransform(); 
      AffineTransform at2 = new AffineTransform(); 

      if (pos != null &&pos2!=null) { 

       Rectangle bounds = box.getBounds(); 
       at.rotate(angle, (bounds.width/2), (bounds.width/2)); 

       Path2D player = new Path2D.Double(box, at); 

       g2d.translate(pos.getX() - (bounds.width/2), pos.getY() - (bounds.height/2)); 
       g2d.setColor(Color.RED); 
       g2d.draw(player); 



      } 

      Rectangle bounds2 = box2.getBounds(); 
       at2.rotate(angle2, (bounds2.width/2), (bounds2.width/2)); 
       Path2D player2 = new Path2D.Double(box2, at2); 

       g2d.translate(pos2.getX() - (bounds2.width/2)+50, pos2.getY() - (bounds2.height/2)); 
       g2d.setColor(Color.RED); 
       g2d.draw(player2); 
      g2d.dispose(); 
     } 

    } 

    public static void applyQualityRenderingHints(Graphics2D g2d) { 

     g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); 
     g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
     g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); 

    } 

} 
+0

一种可能性是“作弊”一点(或者更重要的是,使用可用的API),如果可以生成螺旋的“路径”,则可以使用“PathIterator”来查找所有点沿着那条路径,然后你可以使用它作为你的动画/运动的基础,[例如](http://stackoverflow.com/questions/32392095/how-to-rotate-a-rectangle-after-reaching-specified -position/32397121#32397121) – MadProgrammer

+0

@MadProgrammer如果你检查我对你的解决方案的评论,看看我的更新代码 –

回答

2

因此,根据this idea,您可以利用2D图形API中已有的功能。

困难的部分是让你的螺旋形状设置为Path对象,我们是幸运的,API是非常灵活的...

public class SpiralPath extends Path2D.Double { 

    public SpiralPath(int size) { 
     int numIterations = 5; 
     int arcGrowDelta = (size/numIterations)/2; 
     int arcWidth = 0; 

     int centerX = size/2; 
     int centerY = size/2; 
     moveTo(centerX, centerY); 

     for (int i = 0; i < numIterations; i++) { 
      append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth, 2 * arcWidth, 180, 180, Arc2D.OPEN), true); 
      arcWidth += arcGrowDelta; 
      append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth - arcGrowDelta, 2 * arcWidth, 0, 180, Arc2D.OPEN), true); 
     } 
    } 

} 

Sprial

现在我们的是,其余的是(相对)简单,因为它遵循众所周知的图案......

Sprial

package javaapplication1.pkg005; 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Rectangle; 
import java.awt.RenderingHints; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.geom.AffineTransform; 
import java.awt.geom.Arc2D; 
import java.awt.geom.Path2D; 
import java.awt.geom.PathIterator; 
import java.awt.geom.Point2D; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Test { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public class SpiralPath extends Path2D.Double { 

     public SpiralPath(int size) { 
      int numIterations = 5; 
      int arcGrowDelta = (size/numIterations)/2; 
      int arcWidth = 0; 

      int centerX = size/2; 
      int centerY = size/2; 
      moveTo(centerX, centerY); 

      for (int i = 0; i < numIterations; i++) { 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth, 2 * arcWidth, 180, 180, Arc2D.OPEN), true); 
       arcWidth += arcGrowDelta; 
       append(new Arc2D.Double(centerX - arcWidth, centerY - arcWidth, 2 * arcWidth - arcGrowDelta, 2 * arcWidth, 0, 180, Arc2D.OPEN), true); 
      } 
     } 

    } 

    public Test() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     private SpiralPath spiralPath; 
     private final Rectangle box; 

     private List<Point2D> points; 
     private double angle; 
     private Point2D pos; 
     private int index; 

     protected static final double PLAY_TIME = 5000; // 5 seconds... 

     private Long startTime; 

     public TestPane() { 
      spiralPath = new SpiralPath(150); 
      box = new Rectangle(0, 0, 10, 10); 

      points = new ArrayList<>(25); 
      PathIterator pi = spiralPath.getPathIterator(null, 0.01); 
      while (!pi.isDone()) { 
       double[] coords = new double[6]; 
       switch (pi.currentSegment(coords)) { 
        case PathIterator.SEG_MOVETO: 
        case PathIterator.SEG_LINETO: 
         points.add(new Point2D.Double(coords[0], coords[1])); 
         break; 
       } 
       pi.next(); 
      } 

      pos = points.get(0); 
      Timer timer = new Timer(40, new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 

        if (startTime == null) { 
         startTime = System.currentTimeMillis(); 
        } 
        long playTime = System.currentTimeMillis() - startTime; 
        double progress = playTime/PLAY_TIME; 
        if (progress >= 1.0) { 
         progress = 1d; 
         ((Timer) e.getSource()).stop(); 
        } 

        int index = Math.min(Math.max(0, (int) (points.size() * progress)), points.size() - 1); 

        pos = points.get(index); 
        if (index < points.size() - 1) { 
         angle = angleTo(pos, points.get(index + 1)); 
        } 
        repaint(); 
       } 
      }); 

      timer.start(); 
     } 

     protected double angleTo(Point2D from, Point2D to) { 
      double angle = Math.atan2(to.getY() - from.getY(), to.getX() - from.getX()); 
      return angle; 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      applyQualityRenderingHints(g2d); 
      int x = (getWidth() - spiralPath.getBounds().width)/2; 
      int y = (getHeight() - spiralPath.getBounds().height)/2; 
      g2d.translate(x, y); 
      g2d.draw(spiralPath); 
      AffineTransform at = new AffineTransform(); 

      if (pos != null) { 

       Rectangle bounds = box.getBounds(); 
       at.rotate(angle, (bounds.width/2), (bounds.width/2)); 

       Path2D player = new Path2D.Double(box, at); 

       g2d.translate(pos.getX() - (bounds.width/2), pos.getY() - (bounds.height/2)); 
       g2d.setColor(Color.RED); 
       g2d.draw(player); 

      } 
      g2d.dispose(); 
     } 

    } 

    public static void applyQualityRenderingHints(Graphics2D g2d) { 

     g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); 
     g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); 
     g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 
     g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
     g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); 

    } 

} 
+0

任何人都可以解释downvote吗?答案不回答操作问题吗?我不是想帮助人吗? – MadProgrammer

+0

我不知道是谁做的。主席先生,我有一个问题。如果我需要绘制位于彼此旁边的2个不同螺旋,并且这两个螺旋具有沿着它们中的每一个的螺旋路径以不同速度移动的矩形。我试图在你的代码中复制元素,但我得到了一个经过翻译和移位的螺旋。但是,这两个矩形以相同的速度和方向移动。如果您查看了我上面更新的代码,我将会对您感到满意。 –

+0

螺旋和矩形的位置由g2d.translate控制 – MadProgrammer

0

尝试了一个小程序(没有计时器什么都没有就这面):

protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D)g; 
    g2d.setColor(Color.BLACK); 
    g2d.drawArc(200,200,200,200,0,90); 
    g2d.setColor(Color.magenta); 
    for(double t=0; t<Math.PI/2; t+=Math.PI/100) { 
     int x = 300 + (int)(100 * Math.cos(t)); 
     int y = 300 + (int)(100 * Math.sin(t)); 
     g.fillOval(x, y , 5 , 5); 
    } 
} 

如果您的弧是200宽和高,电弧从0到90(从右侧X轴),这应该绘制弧上的点。

我想你可以概括这对你有什么什么中心宽度/高度等

你也可以改变角度

int y = 300 + (int)(100 * Math.sin(-t)); 

,如果你想向后画。

+0

好吧,我会推广它,但实际上我已经运行你的代码,但它进入一个无限循环,只是打开白色框架和停止。请检查它 –

+0

先生,只需重新定义你的t用双t代替int t,代码就可以正常工作。 我会尽量让对象在这个点上移动 –

相关问题