interference/src/hook.c

65 lines
1.3 KiB
C

#include "hook.h"
#include "conf.h"
#include "level.h"
#include "player.h"
#include "tools.h"
#include <gint/display.h>
#include <stddef.h>
#include <stdlib.h>
static struct Hook_table hook_table = {.hooks = NULL};
static void hook_table_free(void);
void
hook_table_init(void)
{
hook_table_free();
hook_table.n = level_count(HOOK_T);
hook_table.hooks = malloc(hook_table.n * sizeof(struct Hook));
for (int i = 0; i < hook_table.n; ++i) {
hook_table.hooks[i].pos = level_search_s(HOOK_T, i + 1);
hook_table.hooks[i].pos.x =
hook_table.hooks[i].pos.x * TILE_S + TILE_S / 2;
hook_table.hooks[i].pos.y =
hook_table.hooks[i].pos.y * TILE_S + TILE_S / 2;
}
/*hook_table.hooks[0].pos = level_search_s(HOOK_T, 1);*/
}
void
hook_table_free(void)
{
if (hook_table.hooks != NULL) {
hook_table.hooks = NULL;
}
}
int
hook_nb(void)
{
return hook_table.n;
}
struct Vec2
hook_closest(struct Vec2 *pos)
{
/* search the closest hook */
struct Vec2 shortest = {0, 0};
if (hook_table.n) {
shortest = hook_table.hooks[0].pos;
float sh_dist = length(&shortest, pos);
for (int i = 0; i < hook_table.n; ++i) {
struct Hook h = hook_table.hooks[i];
const float dist = length(&h.pos, pos);
if (dist < sh_dist) {
shortest = h.pos;
sh_dist = dist;
}
}
}
shortest = (struct Vec2){shortest.x, shortest.y};
return shortest;
}