簡體   English   中英

觸摸時刪除精靈

[英]Removing sprite when Touched

精靈會每秒生成一次,當觸摸它時,應該將其刪除。

這是我所做的:

//Render the sprites and making them move:
public void draw(SpriteBatch batch) {
    for(Sprite drawEnemy:enemies) {
        drawEnemy.draw(batch);
        drawEnemy.translateY(deltaTime * movement);
        touchInput(drawEnemy.getX(),drawEnemy.getY(),
            drawEnemy.getWidth(),drawEnemy.getHeight(),drawEnemy);
    }
}

//Detecting the touch input:
public void touchInput(float x,float y,float w,float h,Sprite sprite){
    float touchX=Gdx.input.getX();
    float touchY=Gdx.input.getY();

    if(Gdx.input.justTouched()){
        if(touchX > x && touchX < x+w ){
            enemyIterator.remove();
            Pools.free(sprite);
        }
    }
}

已檢測到觸摸輸入,但是我不確定如何刪除它們。
當我觸摸它們時,結果是錯誤。

您無法重用迭代器,因此您的enemyIterator迭代器無效,並且會導致異常。

為了避免這樣做,請更改touchInput方法以僅測試是否應刪除對象,而不是刪除對象。 另請注意,您需要將屏幕坐標轉換為世界坐標,因此也必須使用相機。

private Vector3 TMPVEC = new Vector3();

public boolean touched(float x,float y,float w,float h) {
    TMPVEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(TMPVEC);
    return Gdx.input.justTouched() && TMPVEC.x > x && TMPVEC.x < x+w;
}

您只能在要迭代的地方使用迭代器。 因此,您必須在這樣的循環中獲取本地引用:

public void draw(SpriteBatch batch) {
    for (Iterator<Sprite> iterator = enemies.iterator(); iterator.hasNext();) {
        Sprite drawEnemy = iterator.next();
        drawEnemy.draw(batch);
        drawEnemy.translateY(deltaTime * movement);
        if (touched((drawEnemy.getX(),drawEnemy.getY(), drawEnemy.getWidth(),drawEnemy.getHeight())){
            iterator.remove();
            Pools.free(sprite);
        }
    }
}

但是,上面的內容有點混亂,因為您將更新和繪圖代碼混合在一起,在更新之前進行繪圖,並一遍又一遍地檢查觸摸。 我會這樣重做:

private Vector3 TMPVEC = new Vector3();

public void update (Camera camera, float deltaTime) {
    boolean checkTouch = Gdx.input.justTouched();
    if (checkTouch) {
        TMPVEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(TMPVEC);
    } //This way we only unproject the point once for all sprites

    for (Iterator<Sprite> iterator = enemies.iterator(); iterator.hasNext();) {
        Sprite enemy = iterator.next();
        enemy.translateY(deltaTime * movement);

        if (checkTouch && touched(enemy, TMPVEC)){
            iterator.remove();
            Pools.free(sprite);
        }
    }
}

private void touched (Sprite sprite, Vector3 touchPoint){
    return sprite.getX() <= touchPoint.x && 
        sprite.getX() + sprite.getWidth() <= touchPoint.x;
}

public void draw (SpriteBatch batch){
    for (Sprite sprite : enemies) sprite.draw(batch);
}

在這里,您將在從擁有的類進行draw之前調用update

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM