I want to implement a walk(x,y)
function that lets a sprite move up, down, left, or right exactly one unit. The gameboard is stored in an array where each tile is at the index y*width+x
. So only knowing the current position, width and x and y, I can instantly calculate the new position (and check for obstacles or other stuff). This seems like a very nice solution to me but would this be bad code? Or is is alright in this case?
(A more readible solution would be to use "direction"
as a parameter, but this would bloat the definition of the function itself, which may also lower performance)
Thx in advance!
If your walk(x, y)
function allows putting in more than 1 in distance, this case should also be implemented. Otherwise you would have to check for bad inputs. I would definitely say that it is a bad practice to write functions that are only partially implemented.
If you just want to move a single tile, there is a very elegant solution to this though:
enum class Direction : unsigned {
UP, RIGHT, DOWN, LEFT
};
constexpr int X[4] {
0, 1, 0, -1
};
constexpr int Y[4] {
1, 0, -1, 0
};
void move(Direction d) {
int x = X[static_cast<size_t>(d)];
int y = Y[static_cast<size_t>(d)];
// move by x and y
}
The performance cost is near zero in this case. You're really worried unnecessarily. You can also use a single table instead of two separate ones:
void move(Direction d) {
int x = X[static_cast<size_t>(d)];
int y = X[(static_cast<size_t>(d) + 1) & 0b11];
// move by x and y
}