First off, I'm new to LINQ, so I really don't know what it is. I try to use it in some code per minute, and according to my diagnostics, it is about as fast as using a for loop in the same way. However, I'm not sure how much this will scale, since the lists I work with can grow significantly.
I use LINQ as part of the collision detection function (which still works), and I use it to select a list only for those related to checks.
Here is the LINQ version:
partial class Actor {
public virtual bool checkActorsForCollision(Vector2 toCheck) {
Vector2 floored=new Vector2((int)toCheck.X, (int)toCheck.Y);
if(!causingCollision)
return false;
foreach(
Actor actor in
from a in GamePlay.actors
where a.causingCollision==true&&a.isAlive
select a
)
if(
(actor.location.X>GamePlay.onScreenMinimum.X)
&&
(actor.location.Y>GamePlay.onScreenMinimum.Y)
&&
(actor.location.X<GamePlay.onScreenMaximum.X)
&&
(actor.location.Y<GamePlay.onScreenMaximum.Y)
)
if(actor!=this) {
Vector2 actorfloor=new Vector2((int)actor.location.X, (int)actor.location.Y);
if((floored.X==actorfloor.X)&&(floored.Y==actorfloor.Y))
return true;
}
return false;
}
}
This is my previous method:
partial class Actor {
public virtual bool checkActorsForCollision(Vector2 toCheck) {
Vector2 floored=new Vector2((int)toCheck.X, (int)toCheck.Y);
if(!causingCollision)
return false;
for(int i=0; i<GamePlay.actors.Count; i++)
if(
(GamePlay.actors[i].location.X>GamePlay.onScreenMinimum.X)
&&
(GamePlay.actors[i].location.Y>GamePlay.onScreenMinimum.Y)
&&
(GamePlay.actors[i].location.X<GamePlay.onScreenMaximum.X)
&&
(GamePlay.actors[i].location.Y<GamePlay.onScreenMaximum.Y)
)
if(
(GamePlay.actors[i].isAlive)
&&
(GamePlay.actors[i]!=this)
&&
(GamePlay.actors[i].causingCollision)
) {
Vector2 actorfloor=
new Vector2(
(int)GamePlay.actors[i].location.X,
(int)GamePlay.actors[i].location.Y
);
if((floored.X==actorfloor.X)&&(floored.Y==actorfloor.Y))
return true;
}
return false;
}
}
( ), , , , .