Keeping track of unnamed objects

一笑奈何 提交于 2019-12-04 06:28:28

问题


I want to make a top-down 2d shooting game using libgdx. There will be a lot of bullet objects that I want to keep track of and dispose when they go off the screen. I was thinking that I would use something like

static ArrayList<Bullet> bullets;

to keep track of my bullets in the Bullet class, check this array list for any bullets that are off the screen, dispose of them if they are, and delete that bullet from the ArrayList. I was wondering if this is the best way to do this. It seems like something that should be pretty common and so I wanted to make sure that this is the best way of doing this.


回答1:


Using an object pool is a better approach.

The idea of an object pool is simple and fits perfectly for your needs in this case. The pool handles creating and storing the Bullet objects. All you have to do is to call the obtain method of the pool when you need a bullet (User shoots) and call the recycle method of the pool for this bullet when it's no longer needed in the game (Goes offscreen).

Here is a code example for a pool taken from AndEngine's source. You can use it to learn how it works and make your own pool class (Or use this one).



来源:https://stackoverflow.com/questions/13253535/keeping-track-of-unnamed-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!