Reputation: 125
I want to make a little piece of code that makes and ellipse go toward another point.
The principle is 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 are a couple of problems with that-
double + int = double making it unable to be a possible "x" or "y" for the ellipse.
Slope doesn't update so that it only goes in that direction and stays that way.
And a whole bunch of problems besides. How can I fix this?
Upvotes: 0
Views: 39
Reputation: 6126
There is a little trick in dividing two integers when you expect a double as the return type. You need to explicitly cast the numbers to double before performing the division. here is a quick fix to that I also changed the data types for ellipseX and ellipseY to 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();
}
Upvotes: 2
Reputation: 2682
if you want the slope to follow your mouse pointer then you incorporate inside the loop - I dont know what slope will give you and I'm not sure the equations are right - just answering your this question - also see for int+double
int ellipseX = 30;
int ellipseY = 30;
int ellipse1X = MouseInfo.getPointerInfo().getLocation().x;
int ellipse1Y = MouseInfo.getPointerInfo().getLocation().y;
double slopex = ellipse1X/ellipseX;
double slopey = ellipse1Y/ellipseY;
while(true) {
ellipse1X = MouseInfo.getPointerInfo().getLocation().x;
ellipse1Y = MouseInfo.getPointerInfo().getLocation().y;
slopex = ellipse1X/ellipseX;
slopey = ellipse1Y/ellipseY;
ellipseX=(int)Math.rint(ellipseX+slopex);
ellipseY=(int)Math.rint(ellipseY+slopey);
repaint()
}
public void paintComponent(Graphics g){
g.fillOval(ellipseX, ellipseY, 4, 4);
}
repaint should not be generally called within paint()
Upvotes: 0
Reputation: 5403
The first issue I can see in the code is that you are storing the result of dividing 2 integer variables into a double. If you check, the double will contain a whole number value. Instead, you should do something along the lines of,
double myDouble = (numerator * 1.0) / denominator;
Upvotes: 0