commit 84d158fd94f64aa03ec493d0346e23afe6752c99
parent fc51895afce57b687478fed2d4e60c8978b1a9a5
Author: Matsuda Kenji <info@mtkn.jp>
Date: Tue, 10 Jan 2023 12:58:00 +0900
Implement more efficient collision handler.
It is not yet completed.
Diffstat:
2 files changed, 59 insertions(+), 7 deletions(-)
diff --git a/ex9/main.c b/ex9/main.c
@@ -139,6 +139,7 @@ game_play(void)
ol = NULL;
+ /* setup collision handler */
for (int i = 0; i < NUM_OBJ_TYPE; i++)
for (int j = 0; j < NUM_OBJ_TYPE; j++)
col_func[i][j] = NULL;
@@ -148,7 +149,6 @@ game_play(void)
/* load world into ol */
for (int i = 0; i < WORLD_WIDTH * WORLD_HEIGHT; i++) {
if (world_map[i] == 'b') {
- // TODO: don't forget to free these things.
olc = laddfront(ol, create_object(TBLOCK, 0x00FF00,
i % WORLD_WIDTH * BLOCK_SIZE,
i / WORLD_WIDTH * BLOCK_SIZE,
@@ -188,7 +188,7 @@ game_play(void)
}
}
}
- //lprint(ol, (void (*)(void *))&oprint);
+
while (next_menu == GAME_PLAY){
receive_events(key_state);
handle_inputs(key_state);
@@ -197,6 +197,7 @@ game_play(void)
t0 = ts.tv_nsec;
for (int k = 0; k < SUB_TICK; k++) {
+ // TODO: should be done for ol
next_tick(player, 1e9 / FPS / SUB_TICK);
// game over when fall out of the world
diff --git a/ex9/object.c b/ex9/object.c
@@ -196,14 +196,65 @@ oprint(struct Object *o)
printf("[%d: (%4.0f, %4.0f)]", o->type, o->p.x, o->p.y);
}
+/*
+ * Compare object's x coordinate.
+ */
+int
+olcmpx(struct Object *p, struct Object *q)
+{
+ if(p->p.x < q->p.x)
+ return -1;
+ else if(p->p.x == q->p.x)
+ return 0;
+ else
+ return 1;
+}
+
+/*
+ * sort list of object according to the objects x coordinate.
+ * TODO: change name to better one.
+ */
void
-lhandle_collision(struct List *o)
+olqsortx(struct List *p)
{
- struct List *p, *q;
- for (p = o; p != NULL && p->next != NULL; p = p->next) {
- for (q = p->next; q != NULL; q = q->next) {
- ohandle_collision((struct Object *)p->item, (struct Object *)q->item);
+ lqsort(p, (int (*)(void *, void *))&olcmpx);
+}
+
+/*
+ * The order of list o will be changed.
+ */
+void
+lhandle_collision(struct List *p)
+{
+ olqsortx(p);
+ struct List *stack, *last, *tmp;
+ stack = last = NULL;
+ for (; p != NULL; p = p->next) {
+ //printf("last: ");
+ //lprint(last, (void (*)(void *))&oprint);
+ // if p doesn't have intersection with an item in the stack
+ if (last != NULL &&
+ ((struct Object *)last->item)->p.x +
+ ((struct Object *)last->item)->body.rectangle.w <=
+ ((struct Object *)p->item)->p.x) {
+ // handle collision among the items in the stack.
+ struct List *s, *t;
+ for (s = stack; s != NULL && s->next != NULL; s = s->next)
+ for (t = s->next; t != NULL; t = t->next)
+ ohandle_collision((struct Object *)s->item,
+ (struct Object *)t->item);
+ lfree(stack);
+ stack = NULL;
+ }
+ tmp = laddfront(stack, p->item);
+ if (tmp == NULL) {
+ fprintf(stderr, "lhandle_collision: Error. add item to stack\n");
+ exit(1);
+ }
+ if (stack == NULL) {
+ last = tmp;
}
+ stack = tmp;
}
return;
}