C++/SDL-矩形坐标映射

C++/SDL - Rectangle Coordinates Mapping

本文关键字:坐标 映射 SDL- C++      更新时间:2023-10-16

我正在使用SDL开发一款2D游戏。最近,我实现了各种使对象(及其矩形)运动的功能,但遇到了性能问题,这些问题很可能是由矩形坐标的低效映射引起的。请参阅以下内容:

每当调用move()时,矩形的二维坐标都存储在一个整数数组中。例如,坐标[0]是x轴上的第一个点,坐标[1]是x轴的最后一个点。坐标[2]和[3]适用于y轴上的点。

map()函数获取矩形的坐标,并将它们存储在静态std::map(Status类)中。每个x和y对要么是0,要么是1,这取决于是否存在矩形。玩家的坐标未映射。

当玩家移动时,bool函数collapse()会检查玩家的矩形是否在特定方向上与另一个重弹相邻。如果没有矩形挡道,玩家可以移动。

一切都很好,但map()函数中的所有for循环似乎都占用了大量CPU。当矩形在屏幕上移动时,程序会严重滞后。如何更有效地映射矩形坐标?

void move(int x, int y) {
dstRect.x = x;
dstRect.y = y;
coordinate[0] = dstRect.x;
coordinate[1] = dstRect.x + dstRect.w;
coordinate[2] = dstRect.y;
coordinate[3] = dstRect.y + dstRect.h;
}
void map() {
for (int x = coordinate[0]; x != coordinate[1]; x++) {
for (int y = coordinate[2]; y != coordinate[3]; y++) {
Status::map().insert(std::pair<std::vector<int>, int>({ x, y }, 1));
}
}
}
bool collide(DIRECTION direction) {
if (direction == UP || direction == DOWN) {
for (int x = texture.coordinate[0]; x != texture.coordinate[1]; x++) {
if (direction == UP) {
if (Status::map().find({ x, texture.coordinate[2] - 1 })->second == 1) { return true; }
}
if (direction == DOWN) {
if (Status::map().find({ x, texture.coordinate[3] + 1 })->second == 1) { return true; }
}
}
}
if (direction == RIGHT || direction == LEFT) {
for (int y = texture.coordinate[2]; y != texture.coordinate[3]; y++) {
if (direction == RIGHT) {
if (Status::map().find({ texture.coordinate[1] + 1, y })->second == 1) { return true; }
}
if (direction == LEFT) {
if (Status::map().find({ texture.coordinate[0] - 1, y })->second == 1) { return true; }
}
}
}
return false;
}
void moveRight() {
for (int i = 0; i < speed; i ++) {
if (!collide(RIGHT)) {
int x = texture.dstRect.x + 1;
int y = texture.dstRect.y;
texture.move(x, y);
}
}
}

遵循@FrançoisAndrieux的建议,创建了用于存储坐标的多维向量。