如何從矩形數組中刪除隨機矩形? (How to remove random rectangle from rectangle array?)


問題描述

如何從矩形數組中刪除隨機矩形? (How to remove random rectangle from rectangle array?)

我正在製作一個類似 Whack‑a‑mole 的遊戲,並以矩形數組的形式創建它們,並且我想每 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:

I suggest to use List instead of iterator. With iterator, you dont know count of elements.

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

(by Vasily RozhinEldar Budagov)

參考文件

  1. How to remove random rectangle from rectangle array? (CC BY‑SA 2.5/3.0/4.0)

#libgdx #java #Android






相關問題

為什麼原生 libmpg123 在帶有 libgdx 的 android 上花費這麼長時間? (Why is native libmpg123 taking so long on android with libgdx?)

睡眠後重新加載應用程序 (Re-load the app after sleep)

獲取實際觸摸位置 LibGDX (Get actual touch position LibGDX)

LibGDX - 只有可拖動的運動 (LibGDX - only draggable movement)

無法解析符號“android” - 在使用 libgdx 在 Android 應用程序中實現 Google Analytics 時 (Cannot resolve symbol 'android' - While implementing Google Analytics in Android App with libgdx)

如何從矩形數組中刪除隨機矩形? (How to remove random rectangle from rectangle array?)

球在傾斜平面上滾動 java libgdx (Ball rolling on an incline plane java libgdx)

libgdx - Intellij 類未找到異常? (libgdx - Intellij class not found exception?)

GL_COLOR_BUFFER_BIT 再生哪個內存? (GL_COLOR_BUFFER_BIT regenerating which memory?)

libGDX - 更改屏幕後的黑色按鈕和文本 (libGDX - Black buttons and text after changing screen)

帶有 9patch 的 LibGdx 標籤背景 (LibGdx label background with 9patch)

如何從平鋪中刪除對象? (How do I remove an object from tiled?)







留言討論