Advertisement
Guest User

Untitled

a guest
Jan 12th, 2020
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1.  
  2.     // blocks the ball could might be touching
  3.     struct {int x,y;} blocks[] =
  4.     {
  5.         {ball_gx+0,ball_gy+0}, {ball_gx+1,ball_gy+0},
  6.         {ball_gx+0,ball_gy+1}, {ball_gx+1,ball_gy+1},
  7.     };
  8.  
  9.     // handle collisions
  10.     for(int i=0; i<LENGTH(blocks); i++)
  11.     {
  12.         // shorten names for readability (blk_x is x position, gx is grid x index)
  13.         int gx=blocks[i].x, gy=blocks[i].y;
  14.         int blk_x=gx*BLOCK_WIDTH, blk_y=gy*BLOCK_HEIGHT, blk_w=BLOCK_WIDTH, blk_h=BLOCK_HEIGHT;
  15.  
  16.         // check if there's a collision in the grid
  17.         if(gx<0 || gx>=GRID_WIDTH || gy<0 || gy>=GRID_HEIGHT) continue;
  18.         if(!state->grid[gx+gy*GRID_WIDTH]) continue;
  19.  
  20.         int x_overlap = ball->x+ball->w >= blk_x  &&  ball->x < blk_x+BLOCK_WIDTH;
  21.         int y_overlap = ball->y+ball->h >= blk_y  &&  ball->y < blk_y+BLOCK_HEIGHT;
  22.         int collision = x_overlap&&y_overlap;
  23.        
  24.         if(!collision) continue;
  25.  
  26.         // decrement the block strength
  27.         state->grid[gx+gy*GRID_WIDTH]--;
  28.  
  29.         // get center point of block and distance from ball to decide which side ball is touching
  30.         float blk_cx=blk_x+blk_w/2.0f, blk_cy=blk_y+blk_h/2.0f;
  31.         float dx = cx-blk_cx, dy = cy-blk_cy;
  32.  
  33.         int side='\0';
  34.         side = fabsf(dx)>fabsf(dy)? (dx<0? 'l':'r') : (dy<0? 'u':'d');         
  35.  
  36.         switch(side)
  37.         {
  38.             case 'l': ball->x = blk_x - ball->w;    if(ball->xv > 0.0f) ball->xv = -ball->xv; break;
  39.             case 'r': ball->x = blk_x + blk_w;      if(ball->xv < 0.0f) ball->xv = -ball->xv; break;
  40.             case 'u': ball->y = blk_y - ball->h;    if(ball->yv > 0.0f) ball->yv = -ball->yv; break;
  41.             case 'd': ball->y = blk_y + blk_h;      if(ball->yv < 0.0f) ball->yv = -ball->yv; break;
  42.         }
  43.         break;
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement