[英]Best way to reference multiple (unknown number of) sprites in libgdx (Android)?
我在一個會產生多個“音符”(子畫面)的游戲上工作。
注釋是隨機創建的。 它們中的每一個都具有隨機速度,並在不同的線程中創建。 Notes類是Sprite類的子類。 它具有2個屬性和1個方法:
(由於隱私原因,我無法發布該課程的代碼)
我目前有一個靜態類“ NoteStack”,該類最多可包含64個對Notes對象的引用。
public class NoteStack {
public Notes[] note_array;
public int stack_len;
public NoteStack(){
note_array = new Notes[64];
stack_len = 0;
}
public void push(Notes n){
if(stack_len<64){
note_array[stack_len] = n;
stack_len++;
Gdx.app.log("push", "pushed");
}
}
public void delete_note(int pos){
if(note_array[pos] != null){
note_array[pos] = null;
for(int i = pos; i<stack_len; i++){
note_array[pos] = note_array[pos+1];
}
note_array[stack_len] = null;
stack_len = stack_len - 1;
}
}
}
這是我的“更新”功能的代碼
public void update(float d, SpriteBatch b){
core.draw(b);
for(int i = 0; i< noteStack.stack_len; i++){
Gdx.app.log("update", "Update function running" + i);
noteStack.note_array[i].changePos(d);
noteStack.note_array[i].draw(b);
// scr_w - screen width , scr_h - screen height
if(noteStack.note_array[i].pos.x > scr_w || noteStack.note_array[i].pos.x < 0 || noteStack.note_array[i].pos.y > scr_h || noteStack.note_array[i].pos.y < 0){
noteStack.delete_note(i);
}
}
}
問題(如您所見)是,每當從NoteStack中刪除一個note對象(即,調用delete_note方法)時,數組中的其他Notes對象都會受到影響。
因此,我的問題是:在LibGDX中引用多個Sprite(注釋)對象的最佳方法是什么?
一般來說,在編程中,永遠不要實現自己的“經典”數據結構,除非確實有必要,並且不能使用或擴展集合類型,因為標准實現已進行了很好的編程和測試,因此使用起來更安全。
在您的情況下,我將使用libGDX Array 。 該類具有add,get,size方法,如果確實需要,可以擴展Array類以具有更新功能。
但簡而言之,如果您替換public Notes[] note_array;
使用public Array<Notes> note_array = new Array<>(true, 64);
並使用get
和remove
以及size
來迭代和管理應該起作用的集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.