Reputation: 43
I have a black targetBox that is used to check the area it covers for the existence of Block objects such as the grey one in the top left hand corner and return a boolean if there is a Block at that position. It's a tile system and I have included one case where it would return "false" and one that would return "true".
I understand I can do something like
public bool checkTargetObjects()
{
if(block.x == target.x && block.y == target.y)
{
return true;
}
else
{
return false;
}
}
But I am unsure of how to look for Block objects at the position. How can I do this?
Upvotes: 2
Views: 2041
Reputation: 9201
Instead of storing the X and Y position of your tiles, save that data as a Rectangle
. The only additional thing you need is the Width and Height of your tiles (which should be a constant somewhere).
So instead of having
public class Block
{
public int X { get; set; }
public int Y { get; set; }
}
you can have
public class Block
{
public Rectangle Area { get; set; }
}
Then you can take all your blocks (Let's say you got them all in a List<Block>
called blocks
) and iterate over them to see which one intersects with your Target :
var blocksInTarget = blocks.Where(b => b.Area.Intersects(target.Area));
where Area
is your rectangle.
If you only want to know if there is a rectangle (and not which ones), you can change that Where
with Any
, which you can read as "Return true if there is any block intersecting my target" :
bool isBlockPresent = blocks.Any(b => b.Area.Intersects(target.Area));
Upvotes: 2
Reputation: 1594
You can create a compare double function like
const THRESH = 1e-3; // define as desired for your application
public bool compareDoubles(double a1, double a2)
{
if( fabs(a1-a2) < THRESH)
return true;
else
return false;
}
This allows for a tolerance from getting ONLY exact matches, which are rare for dobules! Then you would use the function on the x and y dimensions of each object (and z if anyone is using 3D). you could even make THRESH a parameter if there is a significant difference in the tolerance on a per dimension basis.
Upvotes: 0