-2

我真的不明白代码中的哪个位置使角色反弹到右侧而不是计数。

    public void exercise1e() {
    PaintWindow pw = new PaintWindow();
    Random rand = new Random();
    ImageIcon image = new ImageIcon("C:/Users/char.jpg");
    int width = pw.getBackgroundWidth();
    int height = pw.getBackgroundHeight();
    int dx = -2;
    int dy = 0;
    int x = 250;
    int y = rand.nextInt(height-100);

    while(true) {
        pw.showImage(image, x, y);
        PaintWindow.pause(20);
        x += dx;
        y += dy;
        if(x<0) {
            dx = -dx;
            if (x>0) {
        }
    }
}
}
4

1 回答 1

0

如果您到达边界然后将方向更改为相反,dx=-dx 将导致该效果。如果达到左极限,则应应用您的条件。当 x<=0 以及达到右极限 x>=width 时

if(x<=0 || x>=width ) {
    dx = -dx;
}

现在将图像的位置重置为 x。否则,您只是在增加和减少该数字。像:image.setLocation(x,y),我不能确定,因为我不知道你用什么来渲染它。

您当前的 if 语句存在逻辑矛盾。

   if(x<0) {
        Only if x is less than 0 evaluate the next if...
        if (x>0) {
            If x is less than 0 but also is greater than 0, understand the universe.
        }
    }
于 2013-10-02T00:38:37.493 回答