在两点之间移动对象

时间:2014-10-14 07:47:25

标签: java java-8 game-physics

我有三个点,p1(开始),p2(结束)和pos(对象的当前位置),以及运行其中每个帧的方法我需要在点p1p2之间移动对象。

我只需要沿点之间的直线移动物体

2 个答案:

答案 0 :(得分:1)

海峡线的方程是y=mx+c。当你需要在2个点之间移动一个物体时,方程式可以简化为y=mx;所以你可以用你的2个点找到m。y依赖于x和方程式。看这张图片

enter image description here

尝试更改x1,y1 and x2,y2并看到它在这条海峡线上移动。 以下我只是写一个课程,这样你就可以轻松地运行它。

public class AnimationJPanel extends JPanel {
   //edit x1,y1 is starting point x2,y2 is end point
   int x1=0;
   int y1=0;
   int x2=100;
   int y2=100;
   //
   int x=x1;
   int y;
   int r=6;

   int m=(y2-y1)/(x2-x1);

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationJPanel panel = new AnimationJPanel();
                panel.setPreferredSize(new Dimension(400, 300));
                panel.animate();
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.getContentPane().add(panel);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
private Timer timer;

    public AnimationJPanel() {
        setBackground(Color.BLACK);
        setForeground(Color.RED);
        setOpaque(true);
    }

    public void animate() {
        timer = new Timer(15, new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               if(x>=x2){
                   timer.stop();//stop when pass the end point
               }
               x++;
               y = m * x;
               System.out.println("x" + x + "  y" + y);
               repaint();
           }
       });
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(x, y, r, r);
    }
}

答案 1 :(得分:0)

线性插值,A和B之间的线中的任何点,对于值double k(在0和1之间),是:

Point p = B + (A-B)*k;

只需循环for (double k=0; k<=1; k+= deltaK)

相关问题