Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Github: https://github.com/nezvers
- Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
- Twitter: https://twitter.com/NeZversStudio
- */
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- // Physics body
- typedef struct{
- int i;
- }Body;
- typedef struct{
- int count;
- Body *list;
- }Cell;
- typedef struct{
- int width;
- int height;
- Cell *cell;
- }GridMap;
- void init_GridMap(GridMap *grid){
- grid->cell = (Cell*)calloc(grid->width *grid->height, sizeof(Cell));
- }
- Cell* get_cell(GridMap *grid, int x, int y){
- return &grid->cell[x + y*grid->width];
- }
- void add_body_to_cell(Cell *cell, Body *body, int x, int y){
- cell->count++;
- printf("%d \n", cell->count);
- Body *old = cell->list;
- cell->list = (Body*)calloc(cell->count, sizeof(Body));
- memcpy(cell->list, old, sizeof(Body)*(cell->count -1));
- Body *p = cell->list + cell->count;
- p = body;
- free(old);
- }
- void add_body_to_grid(GridMap *grid, Body *body, int x, int y){
- Cell *cell = get_cell(grid, x, y);
- add_body_to_cell(cell, body, x, y);
- }
- void remove_body_from_cell(Cell *cell, Body *body, int x, int y){
- cell->count--;
- Body *old = cell->list;
- cell->list = (Body*)calloc(cell->count, sizeof(Body));
- int j = 0;
- for(int i=0; i < cell->count; i++){
- if(&old[i] != body){
- cell->list[j] = old[i];
- j++;
- }
- }
- free(old);
- }
- void remove_body_from_grid(GridMap *grid, Body *body, int x, int y){
- Cell *cell = get_cell(grid, x, y);
- remove_body_from_cell(cell, body, x, y);
- }
- void destroy_GridMap(GridMap *grid){
- for(int y = 0; y<grid->height; y++){
- for(int x=0; x<grid->width; x++){
- Cell *cell = get_cell(grid, x, y);
- if(cell != NULL){
- free(cell->list);
- }
- }
- }
- free(grid->cell);
- }
- int main(){
- GridMap grid = {0};
- grid.width = 100;
- grid.height = 100;
- init_GridMap(&grid);
- Body body = {0};
- add_body_to_grid(&grid, &body, 25, 40);
- Cell *cell = get_cell(&grid, 25, 40);
- cell->list[0].i = 54;
- printf("body now: %d \n", cell->list[0].i);
- destroy_GridMap(&grid);
- return 0;
- }
Add Comment
Please, Sign In to add comment