我正在学习使用SFML库使用c ++制作2D游戏。我目前正在研究一只飞扬的小鸟克隆。大多数功能都起作用(管道移动,鸟跳/掉下);但是,碰撞检测是不正确的。当它恰好位于两条管道之间时,它应该死了,而那只鸟则死了。 这是碰撞检测代码:
bool checkCollision(int x, int y, int w, int h, int xTwo, int yTwo, int wTwo, int hTwo){
IntRect birdRect(x,y,w,h);
IntRect pipeRect(xTwo,yTwo,wTwo,hTwo);
return birdRect.intersects(pipeRect);
}
void logic(){
if(bird->getY() + 45 > h-150){
gameover = true;
}
int birdX = bird->getX();
int birdY = bird->getY();
int birdW = bird->getW();
int birdH = bird->getH();
for(int i=0;i<pipes.size();i++){
int pipeX = pipes[i]->getX();
int pipeY = pipes[i]->getY();
int pipeW = 150;
int pipeH = pipes[i]->getH();
if(checkCollision(birdX,birdY,birdW,birdH,pipeX,pipeY,pipeW,pipeH)){
cout<<i<<endl;
gameover = true;
}
}
}
如果需要的话,这里是鸟管函数:
class Bird{
private:
//global variables
int y;
int originalY;
int x;
float velocityY;
const float thrust = 30;
float gravity;
int screenH, screenW;
const float w = 110.0;const float h = 80.0;
Texture birdTexture;
private:
//private functions
public:
//public functions
Bird(int grav, int width, int height){
screenH = height;screenW = width;
y = height/2; x = width/4;
originalY = y;
gravity = grav;
velocityY = 0;
birdTexture.loadFromFile("art/bird.png");
}
//inline functions
inline int getY(){return y;}
inline int getX(){return x;}
inline int getW(){return w;}
inline int getH(){return h;}
void Update(){
if(y+40 < screenH){//above ground
velocityY += gravity;
}else if(y+40 < screenH){//below ground
y = screenH-40;
}else{//on ground
if (velocityY > 0 ){
velocityY = 0;
}
}
y += velocityY;
}
void Jump(){
velocityY -= thrust;
velocityY += pow(velocityY,2)*.015;
}
void Draw(RenderWindow& window){
RectangleShape birdShape(Vector2f(w,h));
birdShape.setPosition(x+w/2,y+h/2);
birdShape.setTexture(&birdTexture);
birdShape.setOutlineColor(Color::Black);
birdShape.setOutlineThickness(2.0f);
window.draw(birdShape);
}
};
class Pipe{
private:
//global variables
int x,y;
const float w = 150;
float h;
bool top;
Texture topPipeTexture;
Texture bottomPipeTexture;
private:
//private functions
public:
//public functions
Pipe(int height, int screenW, int screenH, bool isTop){
h = height;
x = screenW;
top = isTop;
topPipeTexture.loadFromFile("art/top pipe.png");
bottomPipeTexture.loadFromFile("art/bottom pipe.png");
if (top){
y = h/2;
}else{
y = screenH - (h/2)-150;
}
}
//inline functions
inline int getX(){return x;}
inline int getY(){return y;}
inline int getH(){return h;}
inline int getW(){return w;}
inline bool isTop(){return top;}
void Update(float speed){
x -= speed;
}
void Draw(RenderWindow& window){
RectangleShape pipeShape(Vector2f(w,h));
if(top){
pipeShape.setTexture(&topPipeTexture);
}else{
pipeShape.setTexture(&bottomPipeTexture);
}
pipeShape.setPosition(x,y-h/2);
pipeShape.setOutlineColor(Color::Black);
pipeShape.setOutlineThickness(2.0f);
window.draw(pipeShape);
}
};