74 lines
2.4 KiB
GDScript
74 lines
2.4 KiB
GDScript
extends KinematicBody
|
|
|
|
onready var util = get_node("/root/Util")
|
|
|
|
export var gravity: float = 2.5
|
|
export var velocity: Vector3 = Vector3.ZERO
|
|
export var velocity_acceleration: float = 5
|
|
export var velocity_friction: float = 5
|
|
export var jump_power: float = 125
|
|
var velocity_factor: Vector3 = Vector3.ONE
|
|
|
|
var target_velocity: Vector3 = Vector3.ZERO
|
|
var is_jumping: bool = false
|
|
var jump_permission: float = 1.0
|
|
|
|
func process_velocity(delta: float):
|
|
# Uses the input from MovementInput to compute and update this node's velocity
|
|
# velocity_acceleration controls gradual speedup whereas velocity_friction
|
|
# controls gradual slowdown
|
|
|
|
# Gravity
|
|
# You can buffer jumps by pressing releaseing the space bar and then pressing it again
|
|
if not is_on_floor():
|
|
target_velocity.y = -gravity
|
|
else:
|
|
velocity.y = max(0.0, velocity.y)
|
|
target_velocity.y = max(0.0, max(target_velocity.y, jump_power * $"../MovementInput".jump_intent * jump_permission))
|
|
if not is_jumping and $"../MovementInput".jump_intent != 0.0 and is_on_floor():
|
|
jump_permission = 0.0
|
|
is_jumping = true
|
|
elif is_jumping and $"../MovementInput".jump_intent == 0.0:
|
|
jump_permission = 1.0
|
|
is_jumping = false
|
|
|
|
|
|
var target_velocity_xz = $"../MovementInput".input_xz
|
|
target_velocity = util.vec2_xz_to_vec3(target_velocity_xz, target_velocity.y)
|
|
|
|
var velocity_xz = util.vec3_xz(velocity)
|
|
|
|
var xz_weight = velocity_acceleration * delta
|
|
if target_velocity_xz.length() < velocity_xz.length():
|
|
xz_weight = velocity_friction * delta
|
|
|
|
var target_xz_length = lerp(velocity_xz.length(), target_velocity_xz.length(), xz_weight)
|
|
if target_velocity_xz != Vector2.ZERO:
|
|
velocity_xz = target_velocity_xz.normalized() * target_xz_length
|
|
elif velocity_xz != Vector2.ZERO:
|
|
velocity_xz = velocity_xz.normalized() * target_xz_length
|
|
|
|
if (target_velocity_xz - velocity_xz).length() <= 0.025:
|
|
velocity_xz = target_velocity_xz
|
|
|
|
var y_weight = velocity_acceleration * delta
|
|
if target_velocity.y < velocity.y:
|
|
y_weight = velocity_friction * delta
|
|
|
|
var velocity_y = lerp(velocity.y, target_velocity.y, y_weight)
|
|
if abs(target_velocity.y - velocity_y) <= 0.025:
|
|
velocity_y = target_velocity.y
|
|
|
|
velocity = util.vec2_xz_to_vec3(velocity_xz, velocity_y) * velocity_factor
|
|
|
|
func increase_velocity_factor(by: Vector3):
|
|
velocity_factor *= by
|
|
|
|
func decrease_velocity_factor(by: Vector3):
|
|
velocity_factor /= by
|
|
|
|
func _physics_process(delta):
|
|
process_velocity(delta)
|
|
velocity = move_and_slide(velocity, Vector3.UP)
|
|
|