为了账号安全,请及时绑定邮箱和手机立即绑定

当所有其他精灵都移动时,为什么 Carpaint 不移动?

当所有其他精灵都移动时,为什么 Carpaint 不移动?

芜湖不芜 2022-11-02 15:33:14
我有一个用于在动画中移动精灵的代码——除了我的一个精灵之外,所有精灵都在移动,我不知道为什么。有人可以解释吗?我的精灵类:abstract class SimpleSprite {   // basic x,y movement,keeps a master list of Sprites   public static final ArrayList<SimpleSprite> sprites = new ArrayList<SimpleSprite>();   float x, y, dx, dy; // position and velocity (pixels/TIMER_MSEC)   public SimpleSprite(float x, float y, float dx, float dy) {      // initial position and velocity      this.x = x;      this.y = y;      this.dx = dx;      this.dy = dy;      sprites.add(this);   }   public void update() { // update position and velocity every n milliSec      // default - just move at constant velocity      x += dx; // velocity in x direction      y += dy; // velocity in y direction   }   abstract public void draw(Graphics2D g2d);       // just draw at current position, no updating.}我的精灵不起作用:class Carpaint extends SimpleSprite {    public Carpaint(float x, float y, float dx, float dy) {        super(x, y, dx, dy);    }    @Override    public void draw(Graphics2D g2d){        g2d.setColor(Color.pink);        g2d.fillRect(50, 50, 40, 60);        g2d.setColor(Color.black);        g2d.drawRect(50, 50, 40, 60);        g2d.drawRect(60, 60, 20, 40);        g2d.fillRect(45, 50, 5, 15);        g2d.fillRect(90, 50, 5 , 15);        g2d.fillRect(45, 95, 5, 16);        g2d.fillRect(90, 95, 5, 16);    }}我的主要:public static void main(String[] args) {    // create and display the animation in a JFrame    final JFrame frame = new JFrame("Animation 2 (close window to exit)");    Animation2 animationPanel = new Animation2(600, 500);    frame.add(animationPanel);    frame.pack();    frame.setLocationRelativeTo(null);    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    frame.setVisible(true);    // add some sprites...    new Square(0, 0, 3, 2, 40);    new Ball(500, 0, -3, 3, 20);    new Ball(0, 500, 2, -5, 30);    new Carpaint(100, 100, 20, -6);}我预计所有精灵都会移动,但汽车不会移动(参见此处:https ://i.gyazo.com/0219127277d2543735b3a4727e7c7e72.mp4 )
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

答案来自@RealSkeptic - 我没有参考xand来粉刷汽车y。新代码:


class Carpaint extends SimpleSprite {

    public Carpaint(float x, float y, float dx, float dy) {

        super(x, y, dx, dy);

    }

    @Override

    public void draw(Graphics2D g2d){

        g2d.setColor(Color.pink);

        g2d.fillRect((int) x, (int) y, 40, 60);

        g2d.setColor(Color.black);

        g2d.drawRect((int) x, (int) y, 40, 60);

        g2d.drawRect((int) x + 10, (int) y + 10, 20, 40);

        g2d.fillRect((int) x-5, (int) y, 5, 15);

        g2d.fillRect((int) x + 40, (int) y, 5 , 15);

        g2d.fillRect((int) x - 5, (int) y + 45, 5, 16);

        g2d.fillRect((int) x + 40, (int) y + 45, 5, 16);

    }

}


查看完整回答
反对 回复 2022-11-02
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信