2013-07-24 133 views
0

我已經使用SDL創建了一個程序,其中矩形在程序的內部不斷碰撞,但碰撞檢查工作不正常。矩形彈跳碰撞檢測

下面是代碼:`

int main(int argc, char *argv[]){ 
//variable Initialization] 
width = height = 45; 
srcX = srcY = 0; 
destY = destX = 0; 
vlc = 1; 
SDL_Init(SDL_INIT_VIDEO); 
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); 
SDL_WM_SetCaption("Bouncing Balls","./ball.jpg"); 
backg = IMG_Load("./back.png"); 
ball = IMG_Load("./ball.jpg"); 
while (checkBounce){ 
    //Increase velocity 
    destX += vlc; 
    destY += vlc; 
    //Collision Checking 
     if (destX < 0){ 
      destX = 0; 
      vlc = -vlc; 
      destX += vlc; 
     } 
     if (destY < 0){ 
      destY = 0; 
      vlc = -vlc; 
      destY += vlc; 
     } 
     if (destY + height > 480){ 
      destY = 480 - height; 
      vlc = -vlc; 
      } 
     if (destX + width > 640){ 
      destX = 640 - width; 
      vlc = -vlc; 
     } 
    if (SDL_PollEvent(&event)){ 
     if (event.type == SDL_QUIT) 
      checkBounce = false; 
    } 
//Applying Surfaces 
applySurface(0, 0, backg, screen); 
applyBall(srcX, srcY, destX, destY, width, height, ball, screen); 
SDL_Flip(screen); 
} 
SDL_Quit(); 
return 0; 
} 

下面是GIF圖像發生了什麼:Bouncing Rectangle.gif

+0

這將是很好,如果你能準確地描述發生了什麼。 –

回答

2

我假設預期的結果是爲矩形的牆壁正確反彈?

您需要將速度分爲x和y分量,而不是使用單個數字。這是因爲速度是二維的。

無論何時檢測到碰撞,您的程序都會導致x和y分量均爲負值。這會導致矩形沿其路徑向後反彈。

這裏有一個編輯:

int main(int argc, char *argv[]){ 
    //variable Initialization] 
    width = height = 45; 
    srcX = srcY = 0; 
    destY = destX = 0; 
    vlcX = 1; 
    vlcY = 1; 
    SDL_Init(SDL_INIT_VIDEO); 
    screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); 
    SDL_WM_SetCaption("Bouncing Balls","./ball.jpg"); 
    backg = IMG_Load("./back.png"); 
    ball = IMG_Load("./ball.jpg"); 
    while (checkBounce){ 
     //Increase velocity 
     destX += vlcX; 
     destY += vlcY; 
     //Collision Checking 
     if (destX < 0){ 
      destX = 0; 
      vlcX = -vlcX; 
      destX += vlcX; 
     } 
     if (destY < 0){ 
      destY = 0; 
      vlcY = -vlcY; 
      destY += vlcY; 
     } 
     if (destY + height > 480){ 
      destY = 480 - height; 
      vlcY = -vlcY; 
      } 
     if (destX + width > 640){ 
      destX = 640 - width; 
      vlcX = -vlcX; 
     } 
     if (SDL_PollEvent(&event)){ 
      if (event.type == SDL_QUIT) 
       checkBounce = false; 
     } 
     //Applying Surfaces 
     applySurface(0, 0, backg, screen); 
     applyBall(srcX, srcY, destX, destY, width, height, ball, screen); 
     SDL_Flip(screen); 
    } 
    SDL_Quit(); 
    return 0; 
} 
+0

泰克斯@Ethan沃利 – darpan1118