I’m currently working on a game whereby I will have a player traversing a 2D matrix. I want to be able to modify the environment around the player based on his location, as part of a rendering process.
Basically, the player will be at point x,y and will have 2 points around him at all times. The player might move x,y points in any direction and I need to know what the old no longer necessary pointers are, and also the new points the player is close to.
I’ve drawn up a quick diagram of what I mean:

I need a list of the old points (in red), and the new points (in green) that I can iterate over to perform actions on.
I’ll be writing this method in C++, so I’m really looking for the sudo-logic steps required to make this happen. I’m about 50% way through my own way of doing it, but I believe it to be wholly inefficient and I also believe that is a simple mathematical way to do this.
Probably the most efficient way would be computing a rectangle-rectangle subtraction that may seem difficult and with a lot of cases, but indeed it’s not that hard:
The above function given two rectangles
AandBreturns a vector of rectangles with the result ofA-B. This vector may be empty (BcoversA) or may have from one to four rectangles (four is whenBis stricly contained inA, thus the result will be a rectangle with a rectangular hole in it).Using this function you can easily compute
new-oldandold-newareas.Note that the coordinate schema used in the above code assumes the point-base coordinate system (not a pixel-based coordinate system):
In the above picture note that horizontal X coordinates of rectangles go from 0 to W (not W-1) and vertical Y coordinates go from 0 to H (and not to H-1).
Pixels are just rectangles of area 1 with coordinates
(x, y)-(x+1, y+1); the center of this pixel is(x+0.5, y+0.5). A rectangle withx0==x1ory0==y1is empty.Note also that the code assumes (and returns) non-empty oriented rectangles, i.e.
x0<x1 && y0<y1.This approach of separating the concept of pixel coordinate from the concept of point coordinate simplifies a lot of the pixel math: for example rectangle area is
width*heightand not(width-1)*(height-1).A little program to test with your input case is the following
and the output of this program is