58 lines
1.8 KiB
C++
58 lines
1.8 KiB
C++
#include "player_body.h"
|
|
#include "core/config/engine.h"
|
|
#include "core/input/input.h"
|
|
#include "macros.h"
|
|
#include "scene/3d/camera_3d.h"
|
|
#include "scene/main/node.h"
|
|
#include "scene/main/viewport.h"
|
|
|
|
void PlayerBody::_bind_methods() {
|
|
BIND_PROPERTY(Variant::FLOAT, target_movement_speed);
|
|
BIND_PROPERTY(Variant::FLOAT, movement_acceleration);
|
|
}
|
|
|
|
void PlayerBody::physics_process(double delta) {
|
|
Vector3 const old_velocity{ get_velocity() };
|
|
Vector3 target_velocity{ get_transformed_input() * this->target_movement_speed };
|
|
target_velocity.y = old_velocity.y;
|
|
set_velocity(old_velocity.move_toward(target_velocity, this->movement_acceleration * delta) + get_gravity() * delta);
|
|
move_and_slide();
|
|
}
|
|
|
|
void PlayerBody::_notification(int what) {
|
|
if (Engine::get_singleton()->is_editor_hint()) {
|
|
return;
|
|
}
|
|
switch (what) {
|
|
default:
|
|
return;
|
|
case NOTIFICATION_ENTER_TREE:
|
|
set_physics_process(true);
|
|
set_process_unhandled_input(true);
|
|
return;
|
|
case NOTIFICATION_PHYSICS_PROCESS:
|
|
physics_process(get_physics_process_delta_time());
|
|
return;
|
|
}
|
|
}
|
|
|
|
void PlayerBody::process_movement_input() {
|
|
this->movement_input = {
|
|
Input::get_singleton()->get_axis("move_left", "move_right"),
|
|
Input::get_singleton()->get_axis("move_forward", "move_backward")
|
|
};
|
|
this->movement_input.normalize();
|
|
}
|
|
|
|
void PlayerBody::unhandled_input(Ref<InputEvent> const &what) {
|
|
if (what->is_action("move_forward") || what->is_action("move_backward") || what->is_action("move_left") || what->is_action("move_right")) {
|
|
process_movement_input();
|
|
}
|
|
}
|
|
|
|
Vector3 PlayerBody::get_transformed_input() const {
|
|
Basis const basis{ get_viewport()->get_camera_3d()->get_global_basis() };
|
|
Vector3 forward{ basis.get_column(2) };
|
|
Vector3 left{ basis.get_column(0) };
|
|
return forward * this->movement_input.y + left * this->movement_input.x;
|
|
}
|