Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // blocks the ball could might be touching
- struct {int x,y;} blocks[] =
- {
- {ball_gx+0,ball_gy+0}, {ball_gx+1,ball_gy+0},
- {ball_gx+0,ball_gy+1}, {ball_gx+1,ball_gy+1},
- };
- // handle collisions
- for(int i=0; i<LENGTH(blocks); i++)
- {
- // shorten names for readability (blk_x is x position, gx is grid x index)
- int gx=blocks[i].x, gy=blocks[i].y;
- int blk_x=gx*BLOCK_WIDTH, blk_y=gy*BLOCK_HEIGHT, blk_w=BLOCK_WIDTH, blk_h=BLOCK_HEIGHT;
- // check if there's a collision in the grid
- if(gx<0 || gx>=GRID_WIDTH || gy<0 || gy>=GRID_HEIGHT) continue;
- if(!state->grid[gx+gy*GRID_WIDTH]) continue;
- int x_overlap = ball->x+ball->w >= blk_x && ball->x < blk_x+BLOCK_WIDTH;
- int y_overlap = ball->y+ball->h >= blk_y && ball->y < blk_y+BLOCK_HEIGHT;
- int collision = x_overlap&&y_overlap;
- if(!collision) continue;
- // decrement the block strength
- state->grid[gx+gy*GRID_WIDTH]--;
- // get center point of block and distance from ball to decide which side ball is touching
- float blk_cx=blk_x+blk_w/2.0f, blk_cy=blk_y+blk_h/2.0f;
- float dx = cx-blk_cx, dy = cy-blk_cy;
- int side='\0';
- side = fabsf(dx)>fabsf(dy)? (dx<0? 'l':'r') : (dy<0? 'u':'d');
- switch(side)
- {
- case 'l': ball->x = blk_x - ball->w; if(ball->xv > 0.0f) ball->xv = -ball->xv; break;
- case 'r': ball->x = blk_x + blk_w; if(ball->xv < 0.0f) ball->xv = -ball->xv; break;
- case 'u': ball->y = blk_y - ball->h; if(ball->yv > 0.0f) ball->yv = -ball->yv; break;
- case 'd': ball->y = blk_y + blk_h; if(ball->yv < 0.0f) ball->yv = -ball->yv; break;
- }
- break;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement