📄 axissort.cpp
字号:
#include <vector>
#include <algorithm>
#include <iostream>
class SpriteRect
{
public:
SpriteRect(int x_, int y_, int w_, int h_)
: x(x_), y(y_), w(w_), h(h_) {}
// Position
int x,y;
// Size
int w,h;
};
typedef std::vector<SpriteRect> SpriteVector;
typedef std::vector<SpriteRect>::iterator SpriteIterator;
void FullCollisionTest(const SpriteRect& s1, const SpriteRect& s2)
{
// Here we'll plug in the full collision test.
std::cout << "Testing for collision between: " <<
s1.x << ',' << s1.y << ',' << s1.w << ',' << s1.h << " and " <<
s2.x << ',' << s2.y << ',' << s2.w << ',' << s2.h << std::endl;
}
// Predicate function. Used in the sort to determine
// how to order two sprite objects.
bool PredX(const SpriteRect& s1, const SpriteRect& s2)
{
return (s1.x < s2.x);
}
// Check if two sprites intersect in the X axis
// This assumes that s1.x <= s2.x
bool IntersectX(const SpriteRect& s1, const SpriteRect& s2)
{
return (s2.x < s1.x+s1.w);
}
void axis_sort(SpriteIterator begin, SpriteIterator end)
{
// Sort the objects, according to the X axis
std::sort(begin,end,PredX);
// Go over all objects, according to sorted order
for(;begin!=end;begin++)
{
// Go over all adjacent objects, until no intersection
// in the X axis is found.
for(SpriteIterator i=begin+1;i!=end;i++)
{
if (IntersectX(*begin,*i))
{
// Intersection in X means possible collision
FullCollisionTest(*begin,*i);
}
else
break;
}
}
}
// Test example
int main(int argc, char* argv[])
{
SpriteVector objects;
objects.push_back(SpriteRect(20,6,3,2));
objects.push_back(SpriteRect(7,9,3,2));
objects.push_back(SpriteRect(19,1,3,2));
objects.push_back(SpriteRect(2,4,3,2));
objects.push_back(SpriteRect(18,7,3,2));
objects.push_back(SpriteRect(12,2,3,2));
axis_sort(objects.begin(),objects.end());
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -