【问题标题】:Issue comparing doubles比较双打的问题
【发布时间】:2013-12-07 07:18:42
【问题描述】:

这个简单的 if 比较不起作用,我不知道为什么。

代码:

public abstract class Button extends Drawable_object {
...

@Override
public void update()
{
    super.update();
    mouseOver_last = mouseOver;

    double mx = Game_logic.get_mouse_x();
    double my = Game_logic.get_mouse_y();

    //the not working statement check:
    if ((mx <= x + ((double)width / 2))&&
       (mx >= x  - ((double)width / 2))&&
       (my >= y  - ((double)height / 2))&&
       (my <= y  + ((double)height / 2)))
    { mouseOver = true;}
    else mouseOver = false;
    ....
    }

虽然 Game_logic.get_mouse_x() 和 y 是静态方法:

public class Game_logic {
...

public static double get_mouse_x() { return mouse_x; }
public static double get_mouse_y() { return mouse_y; }
}

这些是由 Mouse adapaer 在我的主运行类中设置的:

 public Board() throws IOException, URISyntaxException {
 ...

 private class MAdapter2 extends MouseAdapter {
    @Override
    public void mouseMoved(MouseEvent e) {
        Game_logic.set_mouse_x(e.getX());
        Game_logic.set_mouse_y(e.getY());
    }

}

问题是,当我在屏幕上绘制 x - width / 2、mx 和 x + width / 2(与 y 相同)时,将鼠标保持在我想要的位置看起来像是陈述必须是真的,但 mouseOver 仍然是错误的。我该如何解决?

【问题讨论】:

标签: java comparison mouse collision


【解决方案1】:

这并不能直接回答您的问题,我只是表明您的 if 陈述有可能成真。我相信您应该打印出 mx,my 并将它们与您期望的值进行比较。这可能是您的问题所在。显然,您还应该检查您选择的 x,y,width,height

public static void main(String[] args) {
    boolean mouseOver;
    int width = 50;
    int height = 50;
    double x = 40;
    double y = 40;
    double mx = 40;
    double my = 40;
    if ((mx <= x + ((double) width / 2)) && (mx >= x  - ((double) width / 2))
            && (my >= y  - ((double) height / 2)) 
            && (my <= y  + ((double) height / 2))) { 
        mouseOver = true;
    } else {
        mouseOver = false;
    }
    System.out.println(mouseOver);
}

请打印出 mx,my,x,y,width,heigh 的所有值并将它们发布并与您认为的值进行比较。

【讨论】:

  • 嗯,可能我没有t express myself clear enough, but I do print out all those variables on screen. Heres 截图:link
  • 呵呵,没关系,发现这是其他问题引起的,所以我可能会为此创建单独的线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多