feat: added player body class

This commit is contained in:
Sara Gerretsen 2026-04-25 19:04:34 +02:00
parent bdcf5f81a1
commit 07d69bf55e
7 changed files with 159 additions and 1 deletions

View file

@ -0,0 +1,51 @@
#include "player_body.h"
#include "core/input/input.h"
#include "scene/main/viewport.h"
void PlayerBody::update_movement() {
Vector3 velocity{ get_velocity() };
Vector3 world_input{ world_move_input().normalized() };
velocity.x = world_input.x;
velocity.z = world_input.z;
velocity += get_gravity() * get_physics_process_delta_time();
set_velocity(velocity);
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);
break;
case NOTIFICATION_PHYSICS_PROCESS:
update_movement();
return;
}
}
void PlayerBody::unhandled_input(Ref<InputEvent> const &event) {
if (event->is_action("move_left") || event->is_action("move_right")) {
this->move_input.x = Input::get_singleton()->get_axis("move_left", "move_right");
}
if (event->is_action("move_forward") || event->is_action("move_backward")) {
this->move_input.y = Input::get_singleton()->get_axis("move_backward", "move_forward");
}
}
Vector3 PlayerBody::world_move_input() const {
Basis const basis{ get_viewport()->get_camera_3d()->get_global_basis() };
Vector3 left{ basis.get_column(0) };
left.y = 0.f;
Vector3 forward{ -basis.get_column(2) };
forward.y = 0.f;
return {
left.normalized() * this->move_input.x +
forward.normalized() * this->move_input.y
};
}

View file

@ -0,0 +1,19 @@
#pragma once
#include "scene/3d/physics/character_body_3d.h"
class PlayerBody : CharacterBody3D {
GDCLASS(PlayerBody, CharacterBody3D);
static void _bind_methods() {}
void update_movement();
protected:
void _notification(int what);
void unhandled_input(Ref<InputEvent> const &event) override;
Vector3 world_move_input() const;
private:
float run_speed{ 5.f };
float run_acceleration{ 5.f };
Vector2 move_input{ 0, 0 };
};

View file

@ -1,11 +1,13 @@
#include "register_types.h"
#include "core/object/class_db.h"
#include "player_body.h"
void initialize_viscosity_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
return;
}
ClassDB::register_class<PlayerBody>();
}
void uninitialize_viscosity_module(ModuleInitializationLevel p_level) {