How can I get a list of a rectangle's intersects?

I am trying to check if the rectangle of a warp zone intersects with one of the many player rectangles. They are in different classes. To do this, I would like to retrieve a List of the warp rectangle’s intersecting rectangles and pick out the player rectangles.

Hey @Comma, welcome to the forums.

While I understand your question, there is more information that would be needed to really answer it. Like how your code is setup, where the warp zone Rectangle values live, are you using ECS, or the traditional Entity-Component setup? Without being able to look at your code, I can only make assumptions, so understand that as I make suggestions below.

Depending on how your game code is setup, you may have something similar to a Scene, World or Level class that contains the data for the environment that the player(s) is currently on. I would assume that the Rectangle values for the warp zones are accessible here, as well as the player(s) that are in the world

For example

public class World
{
    public List<Rectangle> WarpZones { get; set; }
    public List<Player> Players { get; set; }

    // other code...
}

In a traditional Entity-Component (not ECS) you’re World (or Scene) would probably do an Update to update all entities in the world

public void Update(GameTime gameTime)
{
    foreach(Player player in Players)
    {
        player.Update(gameTime);
    }
}

If this is similar to your setup, then you have a couple of routes you could take here. You could pass the WarpZone rectangles into the player Update, and perform the checks on the player side. This doesn’t make much sense though, the Player class shouldn’t need to know or be concerned with what a warp zone is.

Another option, is that after performing the update on the player, which would no doubt update it’s position, you could then do warp zone checks within the World (scene) class

public void Update(GameTime gameTime)
{
    foreach(Player player in Players)
    {
        player.Update(gameTime);
        if(IsPlayerInWarpZone(player))
        {
            // do what you need to here when they're in the warp zone
        }
    }
}

private bool IsPlayerInWarpZone(Player player)
{
    foreach(Rectangle warpRect in WarpZones)
    {
        // Check if player rectangle here intersets
        if(warpRect.Intersects(player.Rectangle)
        {
              return true;
        }
    }

   // If this is reached, player did not intersect with any warp zone so return false
    return false;
}

Again, these are generalized suggestions and without knowing more of your code and how things are setup, I can’t give a more solid answer.

1 Like