我刚刚了解到编译器巧妙地将函数和变量的调用替换为它们代表的代码.考虑到这一点,第二种方法实际上会在下面更好(由于清晰度),实际上运行速度与第一种方法一样快?
//check to see if sphere intersects the box
bool BoundingBox::Intersects(BoundingSphere boundingSphere)
{
// check for intersection on each axis by seeing if the radius is large enough to reach the edge of the cube on the
// appropriate side. All must evaluate to true for there to be an intersection.
return (
((boundingSphere.Centre().x < negCorner.x && boundingSphere.Radius() > posCorner.x - boundingSphere.Centre().x) ||
(boundingSphere.Centre().x > posCorner.x && boundingSphere.Radius() > boundingSphere.Centre().x - negCorner.x))
&&
((boundingSphere.Centre().y < negCorner.y && boundingSphere.Radius() > posCorner.y - boundingSphere.Centre().y) ||
(boundingSphere.Centre().y > posCorner.y && boundingSphere.Radius() > boundingSphere.Centre().y - negCorner.y))
&&
((boundingSphere.Centre().z < negCorner.z && boundingSphere.Radius() > posCorner.z - boundingSphere.Centre().z) ||
(boundingSphere.Centre().z > posCorner.z && boundingSphere.Radius() > boundingSphere.Centre().z - negCorner.z)));
}
Run Code Online (Sandbox Code Playgroud)
第二种方法:
//check to see if sphere intersects the box
bool BoundingBox::Intersects(BoundingSphere boundingSphere)
{
bool xIntersects, yIntersect, zIntersects;
xIntersects =
((boundingSphere.Centre().x < negCorner.x && boundingSphere.Radius() > posCorner.x - boundingSphere.Centre().x) ||
(boundingSphere.Centre().x > posCorner.x && boundingSphere.Radius() > boundingSphere.Centre().x - negCorner.x)));
yIntersects =
((boundingSphere.Centre().y < negCorner.y && boundingSphere.Radius() > posCorner.y - boundingSphere.Centre().y) ||
(boundingSphere.Centre().y > posCorner.y && boundingSphere.Radius() > boundingSphere.Centre().y - negCorner.y)));
zIntersects =
((boundingSphere.Centre().z < negCorner.z && boundingSphere.Radius() > posCorner.z - boundingSphere.Centre().z) ||
(boundingSphere.Centre().z > posCorner.z && boundingSphere.Radius() > boundingSphere.Centre().z - negCorner.z)));
return (xIntersects && yIntersects && zIntersects);
}
Run Code Online (Sandbox Code Playgroud)
无法保证您的预期行为 - 编译器必须非常聪明才能确定它在返回结果之前不必计算x/y/z的所有条件.
在第一个版本中,您知道您将在第一次失败的测试中返回.我坚持这一点,并评论和格式化代码,使其更清晰.
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |