0

我目前正在开发一款太空侵略者风格的游戏,但我遇到了多个子弹实例的问题。目前我只能发射一个。我一直试图让它与一个数组列表一起工作,但我似乎无法让它工作。我得到它最接近工作的是,它发射了多发子弹,但它们都从相同的位置产生,因为子弹没有相对于船只的位置产生。当我移除一个超出边界的对象时,游戏也崩溃了。谁能帮我看看我哪里出错了。这是我到目前为止的一些代码,注释掉的部分是我尝试让数组列表工作

    import java.util.ArrayList;
    import org.newdawn.slick.Input;
    import org.newdawn.slick.Graphics;
    import org.newdawn.slick.GameContainer;

    public class Player extends Entity 
    {
 private int speed = 5;
 private ArrayList<Bullet> bulletList;
 private boolean firing;
 private Bullet bullet;

public Player()
{   
    bullet = new Bullet();
    //bulletList = new ArrayList<Bullet>();
    this.setImage("ship");
    this.setPosition(350,450);
    this.setDimenseions(100, 100);
    this.createRectangle();
}

@Override
public void entityLogic(GameContainer gc, int deltaTime) 
{
    Input input = gc.getInput();

    if(input.isKeyDown(Input.KEY_A))
    {
        this.x -= speed;
    }

    if(input.isKeyDown(Input.KEY_D))
    {
        this.x += speed; 
    }

    if(input.isKeyDown(Input.KEY_W))
    {
        this.y -= speed;
    }

    if(input.isKeyDown(Input.KEY_S))
    {
        this.y += speed;
    }

    if(input.isKeyPressed(Input.KEY_SPACE))
    {
        firing = true;
        bullet.x = this.getX()+40;

        //BulletList.add(new Bullet());
    }

    if(firing)
    {
        /*Carries out the logic for the bullet*/

        //for(Bullet b : bulletList)
        //{
            //b.entityLogic(gc, deltaTime);
        //}

        //Moves the bullet negativly along the y axis
        bullet.entityLogic(gc, deltaTime);
    }
}

@Override
public void entityRendering(Graphics g) 
{
    g.drawImage(this.getImage(), this.getX(), this.getY());

    if(firing)
    {
        /*Draws each bullet object in the list*/

        //for(Bullet b : bulletList)
        //{
            //b.entityRendering(g);
        //}

        bullet.entityRendering(g);
    }
}

}
4

1 回答 1

5

首先忘记你的Bullet bullet实例变量。你不需要它,清单就足够了。

另一件事是您可以使用 aLinkedList而不是 anArrayList因为您不需要随机访问并且您必须经常添加和删除项目,当您迭代子弹以检查碰撞时使用 aListIterator<T>并即时删除它们。

最后它应该是这样的:

List<Bullet> bullets = new ArrayList<Bullet>();

public void entityLogic(GameContainer gc, int deltaTime) {
  // since this method is called many times you should shoot a bullet just every X msec
  if (spacebar pressed) {
    // you spawn a new bullet according to player position
    Bullet bullet = new Bullet(player.x,player.y);
    // you add it to the list
    bullets.add(bullet);
  }

  // destroy bullets which are outside the viewport
  for (int i = 0; i < bullets.size(); ++i) {
    Bullet bullet = bullets.get(i);
    if (bullet.isOutsideBounds()) {
      bullets.remove(i);
      i--;      
    }
}

public void entityRendering(Graphics g) {
  for (Bullet bullet : bullets)
    bullets.entityRenering(g);
}
  }

这只是给你一个基本的想法。

我不知道 slick2d 以及它如何管理渲染和逻辑线程,如果它们是两个不同的线程,那么您应该使用同步列表,例如:

List<Bullet> bullets = Collections.synchronizedList(new ArrayList<Bullet>());
于 2013-01-08T02:00:15.913 回答