authority/modules/authority/player_states.cpp

75 lines
2.3 KiB
C++

#include "player_states.h"
#include "core/input/input.h"
#include "core/math/basis.h"
#include "scene/3d/camera_3d.h"
#include "scene/main/viewport.h"
void PlayerInputState::_bind_methods() {}
void PlayerInputState::unhandled_input(Ref<InputEvent> const &what) {
bool const is_move_vertical{ what->is_action("move_forward") || what->is_action("move_backward") };
bool const is_move_horizontal{ what->is_action("move_right") || what->is_action("move_left") };
if (is_move_vertical || is_move_horizontal) {
stack_state_dependent("PlayerMovementState");
get_viewport()->set_input_as_handled();
}
}
void PlayerInputState::state_entered() {
set_process_unhandled_input(true);
}
void PlayerInputState::state_exited() {
set_process_unhandled_input(false);
}
void PlayerMovementState::_bind_methods() {}
void PlayerMovementState::process(double delta) {
Basis const basis{ get_viewport()->get_camera_3d()->get_global_basis() };
Vector2 backward{ basis.get_column(0).x, basis.get_column(0).z };
if (backward.is_zero_approx()) {
backward = Vector2{ basis.get_column(1).x, basis.get_column(1).z };
}
Vector2 const right{ basis.get_column(2).x, basis.get_column(2).z };
get_character()->set_movement((backward.normalized() * this->movement.x + right.normalized() * this->movement.y));
}
void PlayerMovementState::_notification(int what) {
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
switch (what) {
default:
return;
case NOTIFICATION_READY:
set_process_input(true);
return;
case NOTIFICATION_PROCESS:
process(get_process_delta_time());
return;
}
}
void PlayerMovementState::input(Ref<InputEvent> const &what) {
bool const is_move_vertical{ what->is_action("move_forward") || what->is_action("move_backward") };
bool const is_move_horizontal{ what->is_action("move_right") || what->is_action("move_left") };
if (is_move_vertical || is_move_horizontal) {
this->movement = {
Input::get_singleton()->get_axis("move_left", "move_right"),
Input::get_singleton()->get_axis("move_forward", "move_backward")
};
this->movement.normalize();
}
if (this->get_state_active() && this->movement.is_zero_approx()) {
set_state_active(false);
}
}
void PlayerMovementState::state_entered() {
set_process(true);
}
void PlayerMovementState::state_exited() {
set_process(false);
}