2024-02-07 22:04:19 +00:00
|
|
|
class_name MovementComponent
|
2024-02-27 20:05:55 +00:00
|
|
|
extends CharacterComponent
|
2024-02-07 22:04:19 +00:00
|
|
|
|
2024-02-27 20:05:55 +00:00
|
|
|
static var ticks_per_second := ProjectSettings.get_setting("physics/common/physics_ticks_per_second") as float
|
|
|
|
static var gravity := ProjectSettings.get_setting("physics/3d/default_gravity") as float
|
|
|
|
|
|
|
|
@export var body: CharacterBody3D
|
2024-02-07 22:04:19 +00:00
|
|
|
@export var move_speed := 4.5
|
|
|
|
@export var jump_velocity := 4.5
|
2024-02-23 19:13:46 +00:00
|
|
|
@export var deceleration_speed := 20
|
2024-02-07 22:04:19 +00:00
|
|
|
|
|
|
|
var direction: Vector3
|
2024-02-27 20:05:55 +00:00
|
|
|
var physics_position: Vector3
|
2024-02-07 22:04:19 +00:00
|
|
|
|
|
|
|
func _ready():
|
2024-02-27 20:05:55 +00:00
|
|
|
physics_position = character.position
|
|
|
|
character.controlled.connect(on_controlled)
|
2024-02-24 14:30:41 +00:00
|
|
|
|
2024-02-27 20:05:55 +00:00
|
|
|
func _process(delta: float):
|
2024-02-28 11:15:58 +00:00
|
|
|
if (physics_position - character.position).length_squared() < 0.00001:
|
|
|
|
return
|
|
|
|
|
2024-02-27 20:05:55 +00:00
|
|
|
character.position = Math.damp_vector(character.position, physics_position, ticks_per_second * delta)
|
2024-02-07 22:04:19 +00:00
|
|
|
|
2024-02-27 20:05:55 +00:00
|
|
|
func _physics_process(delta: float):
|
|
|
|
begin_physics()
|
|
|
|
move(delta)
|
|
|
|
end_physics()
|
|
|
|
|
|
|
|
func move(delta: float):
|
2024-02-07 22:04:19 +00:00
|
|
|
if direction:
|
|
|
|
body.velocity.x = direction.x * move_speed
|
|
|
|
body.velocity.z = direction.z * move_speed
|
|
|
|
else:
|
2024-02-23 19:13:46 +00:00
|
|
|
body.velocity.x = Math.dampf(body.velocity.x, 0, deceleration_speed * delta)
|
|
|
|
body.velocity.z = Math.dampf(body.velocity.z, 0, deceleration_speed * delta)
|
2024-02-07 22:04:19 +00:00
|
|
|
|
|
|
|
if !body.is_on_floor():
|
|
|
|
body.velocity.y -= gravity * delta
|
|
|
|
|
2024-02-26 22:50:56 +00:00
|
|
|
if !body.velocity:
|
|
|
|
return
|
|
|
|
|
2024-02-07 22:04:19 +00:00
|
|
|
body.move_and_slide()
|
|
|
|
|
2024-02-27 20:05:55 +00:00
|
|
|
func begin_physics():
|
|
|
|
body.global_position = physics_position
|
|
|
|
|
|
|
|
func end_physics():
|
|
|
|
physics_position = body.global_position
|
|
|
|
body.position = Vector3.ZERO
|
2024-02-07 22:04:19 +00:00
|
|
|
|
|
|
|
func can_jump() -> bool:
|
|
|
|
return body.is_on_floor()
|
|
|
|
|
|
|
|
func jump():
|
|
|
|
body.velocity.y = jump_velocity
|
2024-02-27 20:05:55 +00:00
|
|
|
|
|
|
|
func on_controlled(controller: Controller):
|
|
|
|
controller.direction_changed.connect(on_direction_changed)
|
|
|
|
controller.jumped.connect(jump)
|
|
|
|
|
|
|
|
func on_direction_changed(new_direction: Vector3):
|
|
|
|
direction = new_direction
|