Jump to content
  • Advertisement
Sign in to follow this  
rakazak

[XNA] Deleting objects from a list that fullfills certain conditions

This topic is 2567 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, guys. First time poster here.
I am programming my first game at the moment. It's a vertical shooter comparable to space invaders.
I'm stuck at the following task: I have a list where shots are stored and when they collide with an enemy they should get deleted.
At the moment I have done it like this:
Every shot has an index.
In a foreach loop, every shot checks whether it's colliding with an enemy.
If that happens to be true, an integer in that method gets changed to the index of the object and the object in the list gets deleted.
Then the index of all objects after the deleted get subtracted by one.

However I think that this could be greatly simplyfied by having a boolean variable (for example deleteThis) instead of an index integer in the shot class and
use the List.RemoveAll(condition) method to remove all objects where that bool is true.
However I don't know how I could give the condition that a member of a class has to fulfill a certain condition and couldn't find a solution to that problem
anywhere on the internet.
I hope that this doesn't sound too confusing, but my english is nowhere near perfect.
I also hope that this is the right topic for this kind of question. :)

Thanks in advance for any reply.

Share this post


Link to post
Share on other sites
Advertisement
You can use lambdas or explicitly declared functions for the conditional:

// EXPLICIT CONDITIONAL FUNCTION:
// List<Bullet> bullets; // initialized earlier

// use the conditional function declared&defined below:
bullets.RemoveAll(HasDeletionFlag);

// function used for the conditional:
bool HasDeletionFlag(Bullet obj)
{
return obj.deleteThis;
}

// -or-

// LAMBDA (inline conditional function):
// note that the conditional function is inlined with the call.
bullets.RemoveAll(obj => obj.deleteThis);


The RemoveAll method runs the supplied conditional function for each element of the list, and removes the items if the function returns true given the item as a parameter. The conditional logic can be as complex as you like; the evaluation of a single boolean property of the evaluated object is just about the simplest thing you can do here.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!