C++/SDL-矩形坐标映射
C++/SDL - Rectangle Coordinates Mapping
我正在使用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的建议,创建了用于存储坐标的多维向量。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- OpenGL 4.3 错误地将第 4 个纹理坐标映射到与第 3 个纹理坐标相同的位置
- 如何使用 std::multimap 将整数键映射到两个用作多维数组坐标的整数值(对于井字)?
- 如何在三角形曲面细分评估着色器中插值 UV 映射坐标?
- 如何插值像素坐标而不是像素值?需要它来为相机生成校正重映射
- C++/SDL-矩形坐标映射
- 球面坐标映射创建双环状体
- C 椭圆坐标映射
- 我想使用C++映射,以存储一个矩形id的4个坐标,任何人都可以举一个例子吗
- 创建用于将结构坐标存储为键和线号作为值的映射
- Kinect v2 将颜色坐标映射到相机空间
- 仅对从扭曲图像获得的坐标应用重映射,而不对整个图像应用重映射
- 在C++中的OpenGL中将坐标从三维透视投影映射到二维正投影
- 制作一个以坐标为键的std::映射
- 查找/重新映射OpenGL ES坐标平面的边界
- 2d(3d)坐标的哈希映射(即双精度向量)
- 如何映射项目坐标
- Qt中的坐标映射
- 我是否正确地指定了立方体映射的坐标