Files
projecttorches/Player.gd
2024-06-12 11:54:41 +02:00

71 lines
1.7 KiB
GDScript

extends CharacterBody3D
@export var speed = 14 # m/s
@export var fall_acceleration = 75 # m/s^2
@export var jump_impulse = 20 # m/s
@export var bounce_impulse = 16 # m/s
signal hit
var target_velocity = Vector3.ZERO
func _physics_process(delta):
# By default, we are not moving
var direction = Vector3.ZERO
# Check inputs
if Input.is_action_pressed("move_right"):
direction.x += 1
if Input.is_action_pressed("move_left"):
direction.x -= 1
if Input.is_action_pressed("move_back"):
direction.z += 1
if Input.is_action_pressed("move_forward"):
direction.z -= 1
# If in movement, normalize direction and change looking_at
if direction != Vector3.ZERO:
direction = direction.normalized()
$Pivot.basis = Basis.looking_at(direction)
$AnimationPlayer.speed_scale = 4
else:
$AnimationPlayer.speed_scale = 1
$Pivot.rotation.x = PI / 6 * velocity.y / jump_impulse
# Ground velocity
target_velocity.x = direction.x * speed
target_velocity.z = direction.z * speed
# Vertical velocity
if not is_on_floor():
target_velocity.y = target_velocity.y - (fall_acceleration * delta)
# Jumping
if is_on_floor() and Input.is_action_just_pressed("jump"):
target_velocity.y = jump_impulse
for index in range(get_slide_collision_count()):
var collision = get_slide_collision(index)
if collision.get_collider() == null:
continue
if collision.get_collider().is_in_group("mob"):
var mob = collision.get_collider()
if Vector3.UP.dot(collision.get_normal()) > 0.1:
mob.squash()
target_velocity.y = bounce_impulse
break
# Move the character
velocity = target_velocity
move_and_slide()
func die():
hit.emit()
queue_free()
func _on_mob_detector_body_entered(body):
die()