Java图像绘图

时间:2014-11-27 06:04:21

标签: java 2d-games

我正在制作一个简单的二维游戏,但是我在绘制图像方面遇到了麻烦。以下是与问题相关的几个类

private Vector<Bullet> ammo = new Vector<Bullet>(100);

public class Bullet{
    Image img;
    int x, y, speed;
    boolean show;
    Bullet(Image img,int x, int y, int speed, boolean show){
        this.x = x;
        this.y = y;
        this.speed = speed;
        this.img = img;
        this.show = show;
    }
    public void draw(ImageObserver obs) {
        if(show)
            g2.drawImage(img, this.x, this.y, obs);
    }
    public void update(){
        this.y -= 1;
    }
}

public class Movement{
    ....

    Movement(....){
        .....
    }

    public void fly(){
        ......

        ammo.add(new Bullet(bullet1, m.x, m.y, 7, true));
   }



public class MyPlane {

    KeyControl key;
    Movement flight;
    Image img;
    int x, y, speed, move = 0;
    int boom;
    ...
}


public void drawDemo() {   
    ...        
        for(Bullet bullets: ammo)
            bullets.update();
    ...
        for(Bullet bullets: ammo)
            bullets.draw(this);
    }
}

当我调用bullets.draw(this)时,屏幕上实际上没有绘制任何内容。但我知道弹药矢量确实包含正确的信息,例如x坐标,y坐标......顺便说一句,我使用图形2-D。非常感谢任何帮助和/或建议。

 public void paint(Graphics g) {
    if(bimg == null) {
        Dimension windowSize = getSize();
        bimg = (BufferedImage) createImage(windowSize.width, 
                windowSize.height);
        g2 = bimg.createGraphics();
    }
    drawDemo();
    g.drawImage(bimg, 0, 0, this);
}

1 个答案:

答案 0 :(得分:0)

我认为你应该画出这样的图像:

public void draw(Graphics g2) {
    if(show)
        g2.drawImage(img, this.x, this.y, null);
}

然后在您的平面类中,您必须添加 Graphics 作为drawDemo()方法的参数:

public void drawDemo(Graphics g2) {   
...        
    for(Bullet bullets: ammo)
        bullets.update();
...
    for(Bullet bullets: ammo)
        bullets.draw(g2);
}

}

最后在你画的(Graphics g)方法中你称之为:

public void paint(Graphics g) {
   /*
      ...
   */
   drawDemo(g2);
   g.drawImage(bimg, 0, 0, this);
}