java - How can I fix these multiple problems that deal with slope? -


i want make little piece of code makes , ellipse go toward point.

the principle simple enough:

int ellipsex = 30; int ellipsey = 30; int ellipse1x = mouseinfo.getpointerinfo().getlocation().x; int ellipse1y = mouseinfo.getpointerinfo().getlocation().y; //m=(y2-y1)/(x2-x1) double slopex = ellipse1x/ellipsex; double slopey = ellipse1y/ellipsey; public void paintcomponent(graphics g){     g.filloval(ellipsex, ellipsey, 4, 4);     ellipsex+=slopex;     ellipsey+=slopey;     repaint(); } 

now there couple of problems that-

  • double + int = double making unable possible "x" or "y" ellipse.

  • slope doesn't update goes in direction , stays way.

and whole bunch of problems besides. how can fix this?

there little trick in dividing 2 integers when expect double return type. need explicitly cast numbers double before performing division. here quick fix changed data types ellipsex , ellipsey double:

double ellipsex = 30; double ellipsey = 30; int ellipse1x = mouseinfo.getpointerinfo().getlocation().x; int ellipse1y = mouseinfo.getpointerinfo().getlocation().y; //m=(y2-y1)/(x2-x1) double slopex = (double)ellipse1x/ellipsex; double slopey = (double)ellipse1y/ellipsey; public void paintcomponent(graphics g){     g.filloval((int)ellipsex, (int)ellipsey, 4, 4);     ellipsex+=slopex;     ellipsey+=slopey;     repaint(); } 

Comments