42_cube3D/game/manage_keys.c

86 lines
2.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* manage_keys.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 14:14:51 by erey-bet #+# #+# */
/* Updated: 2023/05/05 15:00:40 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "game.h"
void rotate(t_ply *ply, bool right)
{
double old_dir_x;
double old_dir_y;
double old_plane_x;
double old_plane_y;
double speed;
old_dir_x = ply->dir_x;
old_dir_y = ply->dir_y;
old_plane_x = ply->pla_x;
old_plane_y = ply->pla_y;
speed = ROTATIONSPEED * (M_1_PI / 180.0);
if (!right)
speed = -speed;
ply->dir_x = old_dir_x * cos(speed) - old_dir_y * sin(speed);
ply->dir_y = old_dir_x * sin(speed) + old_dir_y * cos(speed);
ply->pla_x = old_plane_x * cos(speed) - old_plane_y * sin(speed);
ply->pla_y = old_plane_x * sin(speed) + old_plane_y * cos(speed);
}
void movement(t_game *game, t_ply *ply, double x, double y)
{
(void)game;
//if(game->map.map[(int)(ply->pos_x + x)][(int)ply->pos_y] == '0')
ply->pos_x += x;
//if(game->map.map[(int)ply->pos_x][(int)(ply->pos_y + y)] == '0')
ply->pos_y += y;
}
int manage_movement(t_game *game, int key)
{
t_ply *ply;
ply = &game->ply;
//printf("dir_x: %f, dir_y: %f\n", ply->dir_x, ply->dir_y);
if (key == MLX_KEY_W)
movement(game, ply, (ply->dir_x * MOVESPEED), (ply->dir_y * MOVESPEED));
else if (key == MLX_KEY_S)
movement(game, ply, -(ply->dir_x * MOVESPEED), -(ply->dir_y * MOVESPEED));
else if (key == MLX_KEY_D)
movement(game, ply, (ply->pla_x * MOVESPEED), (ply->pla_y * MOVESPEED));
else if (key == MLX_KEY_A)
movement(game, ply, -(ply->pla_x * MOVESPEED), -(ply->pla_y * MOVESPEED));
else if (key == MLX_KEY_L)
rotate(ply, true);
else if (key == MLX_KEY_J)
rotate(ply, false);
return (1);
}
int manage_keys(mlx_key_data_t keys, t_game *game)
{
int is_moving;
is_moving = 0;
if (keys.key == MLX_KEY_Q)
mlx_close_window(game->mlx);
else if (keys.key == MLX_KEY_W
|| keys.key == MLX_KEY_S
|| keys.key == MLX_KEY_D
|| keys.key == MLX_KEY_A
|| keys.key == MLX_KEY_ESCAPE
|| keys.key == MLX_KEY_L
|| keys.key == MLX_KEY_J )
is_moving = manage_movement(game, keys.key);
if (is_moving)
return (1);
return (0);
}