42_cube3D/game/manage_keys.c

80 lines
2.6 KiB
C
Raw Permalink Normal View History

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* manage_keys.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 14:14:51 by erey-bet #+# #+# */
2023-06-15 11:21:07 -04:00
/* Updated: 2023/06/15 13:00:31 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "game.h"
2023-06-15 11:21:07 -04:00
static int rotate(t_ply *ply, bool right)
{
2023-05-11 10:25:29 -04:00
double old_dir_x;
double old_dir_y;
double old_plane_x;
double old_plane_y;
double speed;
2023-05-03 11:48:36 -04:00
old_dir_x = ply->dir_x;
old_dir_y = ply->dir_y;
2023-05-03 11:48:36 -04:00
old_plane_x = ply->pla_x;
old_plane_y = ply->pla_y;
2023-05-03 11:48:36 -04:00
speed = ROTATIONSPEED * (M_1_PI / 180.0);
if (!right)
2023-05-03 11:48:36 -04:00
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);
2023-06-15 11:21:07 -04:00
return (1);
2023-05-03 11:48:36 -04:00
}
2023-06-15 11:21:07 -04:00
static int movement(t_ply *ply, double x, double y)
2023-05-03 11:48:36 -04:00
{
2023-05-11 10:25:29 -04:00
ply->pos_x += x;
ply->pos_y += y;
2023-06-15 11:21:07 -04:00
return (1);
2023-05-03 11:48:36 -04:00
}
2023-06-13 08:19:45 -04:00
int manage_movement(t_game *game)
2023-05-03 11:48:36 -04:00
{
t_ply *ply;
2023-06-15 11:21:07 -04:00
int is_moving;
2023-05-03 11:48:36 -04:00
ply = &game->ply;
2023-06-15 11:21:07 -04:00
is_moving = 0;
2023-06-13 08:19:45 -04:00
if (mlx_is_key_down(game->mlx, MLX_KEY_W))
2023-06-15 11:21:07 -04:00
is_moving = movement(ply, (ply->dir_x * MOVESPEED),
(ply->dir_y * MOVESPEED));
if (mlx_is_key_down(game->mlx, MLX_KEY_S))
is_moving = movement(ply, -(ply->dir_x * MOVESPEED),
-(ply->dir_y * MOVESPEED));
if (mlx_is_key_down(game->mlx, MLX_KEY_D))
is_moving = movement(ply, (ply->pla_x * MOVESPEED),
(ply->pla_y * MOVESPEED));
if (mlx_is_key_down(game->mlx, MLX_KEY_A))
is_moving = movement(ply, -(ply->pla_x * MOVESPEED),
-(ply->pla_y * MOVESPEED));
if (mlx_is_key_down(game->mlx, MLX_KEY_RIGHT)
|| mlx_is_key_down(game->mlx, MLX_KEY_L))
is_moving = rotate(ply, true);
else if (mlx_is_key_down(game->mlx, MLX_KEY_LEFT)
|| mlx_is_key_down(game->mlx, MLX_KEY_J))
is_moving = rotate(ply, false);
2023-06-13 08:19:45 -04:00
return (is_moving);
}
2023-06-13 08:19:45 -04:00
int manage_keys(t_game *game)
{
2023-06-13 08:19:45 -04:00
if (mlx_is_key_down(game->mlx, MLX_KEY_ESCAPE))
mlx_close_window(game->mlx);
2023-06-13 08:19:45 -04:00
if (manage_movement(game))
return (1);
return (0);
}