2015-12-03 55 views
1

我正在制作一个类似蝙蝠的游戏,并且我在矩形阵列中创建它们,并且我想每3秒移除一个随机鼹鼠。但我该怎么做呢?
iter.remove(); < =这将删除只有最后一个不是随机的;(如何从矩形数组中删除随机矩形?

private boolean moleKill(Rectangle mole) { 
    Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(),0); 
    camera.unproject(touchPos); 
    if (mole.contains(touchPos.x, touchPos.y)) 
     return true; 
    else 
     return false; 
} 
private void spawnmole(){ 
    if (moles.size<=4){ 
    Rectangle mole = new Rectangle(); 
    mole.x= MathUtils.random(1,3)*200-100; 
    mole.y= MathUtils.random(1,4)*200; 
    mole.width=150; 
    mole.height=113; 
    moles.add(mole); 
    } 
} 

public void render() 
{ 
    Gdx.gl.glClearColor(0, 0.5f, 0, 0); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
    camera.update(); 
    batch.setProjectionMatrix(camera.combined); 
    batch.begin(); 
    if (TimeUtils.timeSinceMillis(timespawn) > 1000) { 
     spawnmole(); 
     timespawn = TimeUtils.millis(); 
    } 

    for (Rectangle mole: moles){ 
     batch.draw(moleimage,mole.x,mole.y); 
    } 

    Iterator<Rectangle> iter = moles.iterator(); 
    while (iter.hasNext()) { 
     Rectangle mole = iter.next(); 
     if (moleKill(mole) == true) { 
      iter.remove(); 
      score=score+10; 
     } 
    } 

    if (TimeUtils.timeSinceMillis(timehide) > 3000) { 
     iter.remove(); 
     timehide = TimeUtils.millis(); 
    } 

    batch.end(); 
} 

回答

1

我建议使用清单,而不是迭代器迭代器,你不知道的元素数

Random r = new Random(); 
public void removeRandomListElement(List list) { 
    int index = r.nextInt(list.size()); 
    list.remove(index); 
}