0

在这个程序中,我想为一列火车制作动画,当火车到达一些 x 坐标时,我想一个接一个地旋转每个火车车厢(矩形)。火车由五辆汽车组成,一个矩形代表一辆汽车。当火车到达某个位置时,我想为轨道变化设置动画(下轨道到上轨道)。所以我想在每辆车到达换轨位置时旋转它。我使用以下代码来执行此操作,但它会一次旋转所有汽车,第一辆汽车 45 度(正确),第二辆汽车 90 和第三辆汽车 135 ......等等。

代码:

private void drawLineBTrain(Graphics g){

    Graphics2D gg = (Graphics2D) g;

    for(int i = 0; i < b.getSize(); i++){            
        if(rotate){
            gg.rotate(-Math.PI/4, b.getCar(i).getPosX(), b.getCar(i).getPosY());
        }
        gg.fillRect(b.getCar(i).getPosX(), b.getCar(i).getPosY(), 80, 24);
    }
}

public void moveLineBTrain(Train t, boolean goRight){

    if(goRight) {
        b = t;
        int x, y;
        for(int i = 0; i < b.getSize(); i++) {
            x = b.getCar(i).getPosX();
            b.getCar(i).setPosX(++x);
            if(x > ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){
                y = 490 + (int)( (double) (-100 * x) / 280 );
                b.getCar(i).setPosY(y);
                rotate = true;
            }
        }
    } else {
        b = t;
        int x, y;
        for(int i = 0; i < b.getSize(); i++) {
            x = b.getCar(i).getPosX();
            b.getCar(i).setPosX(--x);
            if(x > ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){
                y = 490 + (int)( (double) ( -100 * (1344 - x) / 280 ));
                b.getCar(i).setPosY(y);
            }
        }
    }
}
4

1 回答 1

2

我猜你的问题是你错误地旋转了“画布”,旋转了“对象”。你正在做的是:

  1. 您将“画布”旋转 45 度,然后在其上绘制第一个矩形。结果:旋转 45 度的矩形。
  2. 您将“画布”旋转 45 度(再次!),然后在其上绘制第二个矩形。结果:一个矩形旋转了 45 度,第二个矩形旋转了 90 度。

我的猜测是(我现在无法测试代码)您必须将旋转移出 for 循环并在最后撤消对转换矩阵的更改,以便draw不会转换对 Method 的后续调用(旋转)。试试这个并告诉我们它是否有效,如果没有,我会想到更聪明的方法:

private void drawLineBTrain(Graphics g){

    Graphics2D gg = (Graphics2D) g;
    AffineTransform aT = gg.getTransform(); // We store the initial transformation matrix

    for(int i = 0; i < b.getSize(); i++){            

    if(rotate){
            gg.rotate(-Math.PI/4, b.getCar(i).getPosX(), b.getCar(i).getPosY());
    }

        gg.fillRect(b.getCar(i).getPosX(), b.getCar(i).getPosY(), 80, 24);
        gg.setTransform(aT); // We restore the transformation matrix
    }
}

这是直接来自 Sun的关于 Graphics2D Transformations 的好文本。他们是这样说的:

要执行其他转换,例如旋转或缩放,您可以将其他转换添加到 Graphics2D 上下文。这些额外的变换成为渲染过程中应用的变换管道的一部分

这意味着如果您调用该rotate()方法,Graphics2D 上下文(“画布”)将被旋转并保持这种状态,直到您将其旋转回来(或恢复初始转换矩阵)。

于 2012-11-12T18:20:12.617 回答