我正在使用c ++和SFML制作Pong游戏。大多数情况下,碰撞检测效果很好;但是,有时它会彻底失败,没有给出错误消息。它这样做似乎是不可预测的,因此导致这种情况的原因不只是一种情况,这就是为什么我不知道问题出在哪里的原因。这是碰撞检测的代码:
bool circleRectCollisionDetection(int CircleX,int CircleY,int CircleRadius,int RectX,int RectY,int RectWidth,int RectHeight){
int DeltaX = CircleX - max(RectX, min(CircleX, RectX + RectWidth));
int DeltaY = CircleY - max(RectY, min(CircleY, RectY + RectHeight));
return (DeltaX * DeltaX + DeltaY * DeltaY) < (CircleRadius * CircleRadius);
}
在这里被称为:
int ballx = ball->getX();
int bally = ball->getY();
int rotation = ball->getRotation();
int player1x = player1->getX();
int player2x = player2->getX();
int player1y = player1->getY();
int player2y = player2->getY();
//left Paddle
if(circleRectCollisionDetection(ballx,bally,30,player1x,player1y,30,150)){
cout<<"1"<<endl;
ball->setX(player1x+80);
ball->invertXFunc();
}
//right paddle
if(circleRectCollisionDetection(ballx,bally,30,player2x,player2y,30,150)){
cout<<"2"<<endl;
ball->setX(player2x-80);
ball->invertXFunc();
}