2013-04-03 86 views
1

好吧,所以我想要做的就是创建一个简单的java程序,其中包含一个充满对象的阵列列表,在这种情况下,弹跳球可以添加到游戏中。我希望它的工作方式是,你启动程序,它是一个空白的屏幕。你按空间,它创建一个球,从侧面kepp反弹空间弹出,它会产生更多的球。但我的问题是,我添加了更多的球,它将arraylist中的每个项目设置为相同的x和y坐标。哦,即时通讯使用slick2D库,但我不认为这是问题。arraylist中的所有对象都具有相同的值

这里是节目

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; 

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

公共类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); 
} 

}

+0

如果你认为rgettman的回答很好,你可以接受它。 (点击复选标记) – Justin 2013-04-06 00:03:40

回答

8

出现该问题,因为你的实例变量xy等在EntityBallstatic,意思是有各自的整个类只有一个值。每次创建新实例时,这些值都会被覆盖。从EntityBall中的字段声明中删除static,以便为每个创建的球创建不同的值。

+0

它的工作原理是我几乎打垮了并创建了一个数组,并分别创建了55个对象。 – Ephyxia 2013-04-04 00:05:07

相关问题