TheScottymo
TheScottymo

Reputation: 54

Moving an object between two Points

I have three points, p1 (the start), p2 (the end) and pos (the object's current position), and a method that runs every frame inside of which I need to move the object between the points p1 and p2.

I just need to move the object along a straight line between the points

Upvotes: 0

Views: 2362

Answers (2)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9872

Strait line's equation is y=mx+c .when you need to move a object between 2 points ,equation can simplify to y=mx;so you can find m using your 2 points.and y depend on x and the equation.look at this picture

enter image description here

try to change x1,y1 and x2,y2 and see it moving through this strait line. following i just write a class so you can easily run it.

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

Upvotes: 1

Exceptyon
Exceptyon

Reputation: 1582

linear interpolation, any point in the line between A and B is, for a value of double k (between 0 and 1) is:

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

just loop over for (double k=0; k<=1; k+= deltaK)

Upvotes: 0

Related Questions