I'm trying to make an Agar.io simulation, so I'm using MouseMotionListener's mouseMoved method to find the cursor's location, and calculating the difference between the cursor's coordinates and agar's coordinates to calculate the slope for the animation.
Below is the code for the implemented mouseMoved():
private class CursorTracker implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
//cursor location
cursor_x = e.getPoint().getX();
cursor_y = e.getPoint().getY();
//agar location
agar_x = agar.getX();
agar_y = agar.getY();
repaint();
}
public void mouseDragged(MouseEvent e) {}
}
Below is actionPerformed() for the panel's timer:
private class Animator implements ActionListener {
public void actionPerformed(ActionEvent e) {
//adding food
if (count == 30) {
addRandomFood();
count = 0;
}
count++;
//agar animation - functions on slope animation: x changes by 1, y by m
double delta_x = cursor_x - agar_x;
double delta_y = cursor_y - agar_y;
//slope
double m = (delta_y)/(delta_x);
//pass parameters
agar.move(1, m);
repaint();
}
}
And here is the code for the Agar.move() method:
public void move(double x_interval, double y_interval) {
if (x >= 0)
x -= x_interval;
if (y >= 0)
y -= y_interval;
}
My intention is to find out the slope (which is ∆y/∆x), change x by 1 and y by the slope (m) value at every timer's repeat, which should theoretically result in the agar object moving towards the cursor location bit by bit. (correct me if I'm wrong)
Also, the cursor detector (mouseMoved) seems to work weirdly; it works only once, agar doesn't change motion direction even the cursor is relocated. And it might even be not properly "listening" to the cursor and just doing it by default because regardless of the cursor's location when the program starts running, the agar always ends up moving along the x-axis towards the origin.