I have a function that receives an array of Objects.
I also have a class called Rectangle
but when I iterate the array of objects I need the Object in that index to be casted as Rectangle and not as object because the function I will use needs the parameter to be type Rectangle:
//For collision handling - Receives one rectangle
public bool IsColliding(Rectangle collisionRectangle)
{
return this.destinationRect.Intersects(collisionRectangle);
}
//Overloading - Receives an array with multiple Rectangles
public bool IsColliding(Object[] collisionRectangles)
{
for(int i = 0; i <= collisionRectangles.Length; i++)
{
//CODE WILL FAIL HERE - The method "Intersects" requires and object of type Rectangle
if(this.destinationRect.Intersects((Rectangle)collisionRectangles[i]))
{
return true;
}
}
return false;
}
EDIT 1:
Declaration of the array before passing it to the function:
Object[] buildingCollitionRectangles =
{
new Rectangle[144, 16, 96, 32],
new Rectangle[144, 48, 96, 64]
};
Trying to use the method like this:
if(!player.IsColliding(buildingCollitionRectangles))
{
updatePlayerInput();
}
EDIT 2:
Trying to store Rectangles in a Rectangle[] array:
All right, I think we found it - you used square brackets instead of parentheses for the Rectangle
constructor. As is, I think you're actually allocating two enormous multi-dimensional arrays of Rectangle
objects. https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.rectangle.aspx definitely shows you need parentheses.
Try this:
Rectangle[] buildingCollitionRectangles =
{
new Rectangle(144, 16, 96, 32),
new Rectangle(144, 48, 96, 64)
};
(Note that I think this should also solve the problem of not being able to use a Rectangle[]
array)