我想制作一些代码,使椭圆走向另一个点。
原则很简单:
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();
}
现在有几个问题 -
double + int = double使得它无法成为椭圆的“x”或“y”。
斜率不会更新,只会朝那个方向发展并保持这种状态。
除此之外还有很多问题。我该如何解决这个问题?
答案 0 :(得分:2)
当你期望将double作为返回类型时,分割两个整数有一个小技巧。在执行除法之前,您需要明确地将数字转换为加倍。这里有一个快速解决方法,我还将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();
}
答案 1 :(得分:0)
我在代码中可以看到的第一个问题是你存储了将2个整数变量分成double的结果。如果选中,则double将包含整数值。相反,你应该做一些事情,
double myDouble = (numerator * 1.0) / denominator;
答案 2 :(得分:0)
如果你想要斜率跟随你的鼠标指针然后你在循环中加入 - 我不知道斜率会给你什么,我不确定方程是否正确 - 只是回答你的问题 - 也看到了INT +双
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);
}
通常不应在paint()中调用重绘