obj.h (2216B)
1 typedef struct Obj{ 2 float ppx, ppy; //previous position 3 float px, py; //current position 4 float vx, vy; //velocity 5 float ax, ay; //acceleration 6 float m; //mass 7 float width, height; 8 } Obj; 9 10 Obj *obj_create(float px, float py, 11 float vx, float vy, 12 float ax, float ay, 13 float m, 14 float width, float height); 15 void obj_move(Obj *obj, float px, float py); // move obj to the pos 16 void obj_next_tick(Obj *obj, float dt); // move obj by velocity * dt 17 void obj_accel(Obj *obj, float ax, float ay); // accelerate obj by accel 18 int obj_test_collision(Obj *obj1, Obj *obj2); 19 void obj_handle_collision(Obj *obj1, Obj *obj2); 20 21 Obj 22 *obj_create(float px, float py, 23 float vx, float vy, 24 float ax, float ay, 25 float m, 26 float width, float height) 27 { 28 Obj *obj; 29 obj = (Obj *) malloc(sizeof(Obj)); 30 obj->ppx = obj->px = px; 31 obj->ppy = obj->py = py; 32 obj->vx = vx; 33 obj->vy = vy; 34 obj->ax = ax; 35 obj->ay = ay; 36 obj->m = m; 37 obj->width = width; 38 obj->height = height; 39 return obj; 40 } 41 42 void 43 obj_move(Obj *obj, float px, float py) 44 { 45 obj->ppx = obj->px = px; 46 obj->ppy = obj->py = py; 47 } 48 49 void 50 obj_next_tick(Obj *obj, float dt) 51 { 52 obj->ppx = obj->px; 53 obj->ppy = obj->py; 54 obj->vx += obj->ax * dt; 55 obj->vy += obj->ay * dt; 56 obj->px += obj->vx * dt; 57 obj->py += obj->vy * dt; 58 } 59 60 void 61 obj_accel(Obj *obj, float ax, float ay) 62 { 63 obj->vx += ax; 64 obj->vy += ay; 65 } 66 67 68 int 69 obj_test_collision(Obj *obj1, Obj *obj2) 70 { 71 return obj1->py < obj2->py + obj2->height && 72 obj2->py < obj1->py + obj1->height && 73 obj1->px < obj2->px + obj2->width && 74 obj2->px < obj1->px + obj1->width; 75 } 76 77 void 78 obj_handle_collision(Obj *obj1, Obj *obj2) 79 { 80 if(!obj_test_collision(obj1, obj2)) 81 return; 82 83 float v1, v2; 84 float m1 = obj1->m; 85 float m2 = obj2->m; 86 87 if (obj2->ppy + obj2->height <= obj1->ppy || 88 obj1->ppy + obj1->height <= obj2->ppy){ 89 v1 = obj1->vy; 90 v2 = obj2->vy; 91 obj1->vy = 2*m2/(m1+m2)*v2 + (m1-m2)/(m1+m2)*v1; 92 obj2->vy = 2*m1/(m1+m2)*v1 + (m2-m1)/(m1+m2)*v2; 93 }else if (obj2->ppx + obj2->width <= obj1->ppx || 94 obj1->ppx + obj1->width <= obj2->ppx){ 95 v1 = obj1->vx; 96 v2 = obj2->vx; 97 obj1->vx = 2*m2/(m1+m2)*v2 + (m1-m2)/(m1+m2)*v1; 98 obj2->vx = 2*m1/(m1+m2)*v1 + (m2-m1)/(m1+m2)*v2; 99 } 100 101 }