1

我要做的就是创建一个简单的 Java 程序,它有一个充满对象的数组列表,在本例中是弹跳球,可以添加到游戏中。我希望它工作的方式是,你启动程序,它是一个空白屏幕。你按下空间,它会产生一个从侧面反弹的球,通过按下空间它会产生更多的球。我遇到的问题是当我添加更多球时,它会将数组列表中的每个项目设置为相同的 x 和 y 坐标。我正在使用 slick2D 库,但我认为这不是问题所在。

这是程序的主要部分

public static ArrayList<EntityBall> ballList;

    @Override
    public void init(GameContainer gc) throws SlickException {
        ballList = new ArrayList<EntityBall>();
    }

    @Override
    public void update(GameContainer gc, int delta) throws SlickException {
        String TITLE = _title + " | " + gc.getFPS() + " FPS" + " | " + ballList.size() + " entities";
        frame.setTitle(TITLE);

        Input input = gc.getInput();

        if (input.isKeyPressed(Input.KEY_SPACE)) {
            addBall();
        }
    }

    public void render(GameContainer gc, Graphics g) throws SlickException {
        for(EntityBall e : ballList) {
            e.render(g);
        }
    }

    public static void addBall() {
        ballList.add(new EntityBall(getRandom(0, _width - ballWidth), getRandom(0, _height - ballWidth), 20, 20));
    }

    public static int getRandom(int min, int max) {
        return min + (int) (Math.random() * ((max - min) + 1));
    }

这是 EntityBall 类

package me.Ephyxia.Balls;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;

public class EntityBall {

    public static int x;
    public static int y;
    public static int height;
    public static int width;
    
    public EntityBall(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public void render(Graphics g){
        g.fillOval(x, y, width, height);
    }
}
4

1 回答 1

8

出现问题是因为您的实例变量x,yEntityBallstatic,这意味着整个类中的每个变量只有一个值。每次创建新实例时,这些值都会被覆盖。static从 中的字段声明中删除EntityBall,以便创建的每个球都有不同的值。

于 2013-04-03T21:01:11.660 回答