我正在尝试使用DirectX TK(即Vector2类)实现分离轴定理(SAT)冲突检测。但是我给出错误的功能
抛出异常:读取访问冲突。birdPoints为0x441D0112。发生
这是该功能的代码:
bool Bird::collisionDetection()
{
Vector2 birdPointsArr[5];
Vector2*birdPoints = getBirdPoints(birdPointsArr);
Vector2 pipePointsArr[5];
Vector2* pipePoints = getPipePoints(pipePointsArr,0);
Vector2* axes = new Vector2[9];
//create array of axes for bird
for (int i = 0; i < 5; i++)
{
Vector2 p1 = birdPoints[i];
Vector2 p2 = birdPoints[i + 1 == 5 ? 0 : i + 1];
Vector2 edge = Vector2(p1.x - p2.x, p1.y - p2.y);
Vector2 normal = Vector2(-edge.y, edge.x);
axes[i] = normal;
}
//create array of axes for pipe
for (int i = 5; i < 9; i++)
{
Vector2 p1 = pipePoints[i];
Vector2 p2 = pipePoints[i + 1 == 5 ? 0 : i + 1];
Vector2 edge = Vector2(p1.x-p2.x, p1.y-p2.y);
Vector2 normal = Vector2(-edge.y, edge.x);
axes[i] = normal;
}
//loop over every axis
for (int i = 0; i < 9; i++)
{
double minBird = axes[0].Dot(birdPoints[0]);
double maxBird = minBird;
double minPipe = axes[0].Dot(pipePoints[0]);
double maxPipe = minPipe;
//projects every bird vertex to get min and max
for (int j = 1; j < 5; i++)
{
double p = axes[i].Dot(birdPoints[j]);
if (p < minBird) {
minBird = p;
}
else if (p > maxBird) {
maxBird = p;
}
}
//projects every pipe vertex to get min and max
for (int j = 1; j < 4; i++)
{
double p = axes[i].Dot(pipePoints[j]);
if (p < minPipe) {
minPipe = p;
}
else if (p > maxPipe) {
maxPipe = p;
}
}
if (maxBird < minPipe || maxPipe < minBird)
{
return true;
}
}
delete[] axes;
return true;
}
这里是getBirdPoints()
和getPipePoints()
的代码:
Vector2* Bird::getPipePoints(Vector2* points, int index)
{
auto pipe = pipes[index];
//upper pipe
points[0] = Vector2(0, 0);
points[1] = Vector2(pipe->getW(), 0);
points[2] = Vector2(pipe->getW(), 0);
points[3] = Vector2(0, pipe->getH());
points[4] = Vector2(0, pipe->getGapH()+pipe->getGapSize()/2);
points[5] = Vector2(pipe->getW(), pipe->getGapH() + pipe->getGapSize() / 2);
points[6] = Vector2(pipe->getW(), 2*(pipe->getGapH() + pipe->getGapSize()));
points[7] = Vector2(0, 2 * (pipe->getGapH() + pipe->getGapSize()));
return points;
}
Vector2* Bird::getBirdPoints(Vector2* points)
{
points[0] = Vector2(36+screenPos.x,0+screenPos.y);
points[1] = Vector2(68+screenPos.x, 0+screenPos.y);
points[2] = Vector2(100+screenPos.x, 44+screenPos.y);
points[3] = Vector2(57+screenPos.x, 70+screenPos.y);
points[4] = Vector2(0+screenPos.x, 32+screenPos.y);
return points;
}
另外,还有一个单独的注释,它不需要这种for循环就可以有更好的算法。谢谢!