Java-Gaming.org Hi !
Featured games (90)
games approved by the League of Dukes
Games in Showcase (736)
Games in Android Showcase (224)
games submitted by our members
Games in WIP (813)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Getting rid of an object  (Read 1630 times)
0 Members and 1 Guest are viewing this topic.
Offline hansielneff

Senior Newbie


Exp: 1-3 months



« Posted 2015-05-02 15:33:23 »

I'm making a Space Invaders game, but I have a problem.

When the player presses the 'space' button, the game creates a new object of the class 'Bullet'.
When a bullet hits an enemy, I'd like for the bullet and the enemy to be removed and forgotten completely. I don't want the computer to waste any power on checking if they're still there and should be rendered. How would I do this?

I'm making my games in pure Java, btw!
Offline chrislo27
« Reply #1 - Posted 2015-05-02 15:41:54 »

I'm assuming you're storing your Bullets in some form of list, perhaps an ArrayList. ArrayList has some methods that you can use to remove things. They are:
1  
2  
3  
4  
remove(int)
remove(Object)
removeAll(Collection)
removeRange(int start, int end)


The first method removes the object at the index number you specify. This is the fastest method because compared to the next method (remove(Object)), it doesn't have to search the list for said object.
The second object removes the object you specify, if it exists. This is ever so slightly slower because it searches for the object first.
The third and fourth object is for removing bunches of objects. Since you're only removing one Bullet class at a time, I don't think you'll need these two just yet.

Basically, when your bullet hits an enemy and deals damage, you can call the remove method on the list containing the bullet objects.

If you want to be more efficient (warning, more advanced content):
You could "pool" bullets. Creating and removing an object every single time isn't great for memory, and the JVM has to constantly re-instantiate objects. You could "pool" them instead. Pooling is storing leftover objects to be reused for later! Here's a good wiki article on pooling (it's for libgdx, but the concept is still the same).
Offline BurntPizza

« JGO Bitwise Duke »


Medals: 485
Exp: 7 years



« Reply #2 - Posted 2015-05-02 17:51:13 »

Consideration: remove()ing lots of times in a large arraylist can be slow because all the elements after the removed one have to be shifted over each time.
This idiom can be used to prevent this if the ordering of the elements doesn't matter:

1  
2  
3  
4  
5  
6  
7  
8  
9  
// { written in post }
// copy last element onto to-be-removed element, pop now-duplicate last element
public static <E> E unorderedRemove(ArrayList<E> list, int idx) {
    E obj = list.get(idx);
    E last = list.remove(list.size() - 1);
    if (idx != list.size())
        list.set(idx, last);
    return obj;
}


Also consider: don't use pools without testing if it's actually faster. It's often not, especially for small objects like Bullets, but it depends heavily on the use case.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Husk

Senior Devvie


Medals: 20
Exp: 3 years


Want to learn everything.


« Reply #3 - Posted 2015-05-02 17:57:14 »

BurntPizza beat me to it. It's a nice trick.

I'd also question of use of an Object pool. The JVM seems to cause logical optimizations to ...not really work. Something I tested a while ago was calling new Vector2f() inside a loop, rather than doing it once outside the loop and replacing it. Keeping it inside the loop was much much faster. It's one of the main reasons why I choose not to use Java for projects. However, the time taken to remove an element from a list but be enough to warrant using a pool.

Offline BurntPizza

« JGO Bitwise Duke »


Medals: 485
Exp: 7 years



« Reply #4 - Posted 2015-05-02 18:11:36 »

The typical case I use a pool for is render loops which want a steady stream of frame images. (read: high throughput of large objects) 1080p @ 60 fps is 474 Mb/s allocation/deallocation, which seems to choke at least the default GC pretty badly as you might expect.
Meanwhile pooling yields a constant low memory usage with no major allocation happening in the loop.
Example usage
Offline MrPork
« Reply #5 - Posted 2015-05-02 19:47:23 »

Sorry if what I write seems a bit odd, I'm trying to answer you from a phone. Anyways, what I Tend to do is have an Arraylist for the Bullets and another one for the ships.

So first things first we create them:

1  
2  
public ArrayList<YourShipClass> shipList;
         Public ArrayList<YourBulletClass> bulletList;


Then make sure to instantiate your ArrayLists or you will get a Null Pointer Exception.

1  
2  
shipList = new ArrayList<>();
         bulletList = new ArrayList<>();


You can add objects to an ArrayList like so (for when you press space for your bullets):

1  
 bulletList.add(new Bullet());


Doing the same with the ships, you can then check for collision between the bullets and the ships by constantly looping through both the lists.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
for(Iterator<YourShipClass> shipIter = shipList.iterator; shipIter.hasNext();){
      YourShipClass ship = shipIter.next();
           for(Iterator<YourBulletClass> bulletIter = bulletList.iterator; bulletIter.hasNext();){
                YourBulletClass bullet = bulletIter.next();

        If (bullet intersects with ship){
             bulletIter.remove(); // Removes the bullet that collided
ship.blowThef**kUp();
}
}
}


Again, sorry for any unreadable sections or bad syntax, its quite hard to type on the phone.
Oh, and don't use what I say permanently I'm a noob as well and am only showing you what has worked for me so far. If there's anything I've learned from programming is that there's almost always room for improvement.

"f**k it, maybe it'll work." -Me
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 
cybrmynd (137 views)
2017-08-02 12:28:51

cybrmynd (157 views)
2017-08-02 12:19:43

cybrmynd (151 views)
2017-08-02 12:18:09

Sralse (167 views)
2017-07-25 17:13:48

Archive (640 views)
2017-04-27 17:45:51

buddyBro (764 views)
2017-04-05 03:38:00

CopyableCougar4 (1297 views)
2017-03-24 15:39:42

theagentd (1262 views)
2017-03-24 15:32:08

Rule (1235 views)
2017-03-19 12:43:22

Rule (1310 views)
2017-03-19 12:42:17
List of Learning Resources
by elect
2017-03-13 14:05:44

List of Learning Resources
by elect
2017-03-13 14:04:45

SF/X Libraries
by philfrei
2017-03-02 08:45:19

SF/X Libraries
by philfrei
2017-03-02 08:44:05

SF/X Libraries
by SkyAphid
2017-03-02 06:38:56

SF/X Libraries
by SkyAphid
2017-03-02 06:38:32

SF/X Libraries
by SkyAphid
2017-03-02 06:38:05

SF/X Libraries
by SkyAphid
2017-03-02 06:37:51
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!