1

我一直在尝试用 C 编写一些碰撞检测代码,下面是我目前拥有的函数,它每帧调用一次,但是由于某种原因,当 2 个精灵重叠时,碰撞不起作用

short int Collision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2)
{
    int left1, left2;
    int right1, right2;
    int top1, top2;
    int bottom1, bottom2;

    left1 = x1;
    left2 = x2;
    right1 = x1 + w1;
    right2 = x2 + w2;
    top1 = y1;
    top2 = y2;
    bottom1 = y1 + h1;
    bottom2 = y2 + h2;

    if ((bottom1 < top2)||(top1 > bottom2)||(right1 < left2)||(left1 > right2)) 
    {
        return(1);
    }

    else
    {
        return(0);
    }

    };

    if (Collision ==1)
    {
    //code for collision here
    }

任何指向正确方向的指针将不胜感激

4

2 回答 2

1

我知道,有一个正确的单一条件,有 32 个标签和 16 个运算符,但它无法阅读并且容易搞砸。我的建议是:写更多但更简单的条件。

bool collision = false;
do {
  if (top1 > bottom2) break;  // 1 is under 2
  if (top2 > bottom1) break;  // 1 is beyond 2
  if (left1 > right2) break;  // 1 is right to 2
  if (left2 > right1) break;  // 1 is left to 2
  // I think we listed all the non-collide cases  
  collision = true;
} while (false);

如果“触摸”算作非碰撞,则应使用 >= 代替 > -s。一个好的编译器应该从这个和一个很长的复杂条件生成相同的代码。

于 2012-12-13T22:03:06.810 回答
0

请记住,(0,0) 顶点是左上角而不是左下角。因此,y(垂直轴)向下增加,x(水平轴)向右增加。

所以,bottom1 < top2意味着如果没有碰撞和类似情况是你的其他条件

于 2012-12-13T21:38:42.513 回答