- Edited
extends CharacterBody2D
@export var speed = 300
@export var gravity = 30
@export var jump_force = 300
@export var crouching_speed = 150
@onready var crouch_raycast1 = $CrouchRaycast_1
@onready var crouch_raycast2 = $CrouchRaycast_2
@onready var ap = $AnimationPlayer
@onready var sprite = $Sprite2D
@onready var cshape = $CollisionShape2D
var is_crouching = false
var stuck_under_object = false
var standing_cshape = preload("res://Resources/player_Standing_Collision_Shape.tres")
var crouching_cshape = preload("res://Resources/player_crouching_Collision_Shape.tres")
func _physics_process(delta):
if !is_on_floor():
velocity.y += gravity
if velocity.y> 1000:
velocity.y = 1000
if Input.is_action_just_pressed("jump"): #&& is_on_floor():
velocity.y = -jump_force
var horizontal_direction = Input.get_axis("move_left","move_right")
velocity.x = speed * horizontal_direction
if horizontal_direction != 0:
sprite.flip_h = (horizontal_direction == -1)
if Input.is_action_just_pressed("crouch"):
crouch()
elif Input.is_action_just_released("crouch"):
if above_head_is_empty():
stand()
else:
if stuck_under_object != true:
stuck_under_object = true
print("Player stuck under")
if stuck_under_object && above_head_is_empty():
if !Input.is_action_just_pressed("crouch"):
stand()
stuck_under_object = false
print("Player was stuck")
if is_crouching:
velocity.x = crouching_speed * horizontal_direction
move_and_slide()
update_animation(horizontal_direction)
func above_head_is_empty() -> bool:
var result = !crouch_raycast1.is_colliding() && !crouch_raycast2.is_colliding()
return result
func update_animation(horizontal_direction):
if is_on_floor():
if horizontal_direction == 0:
if is_crouching:
ap.play("Crouch")
else:
ap.play("Idle")
else:
if is_crouching:
ap.play(("Crouch_Walk"))
else:
ap.play("Run")
else:
if velocity.y < 0:
ap.play("Jump")
elif velocity.y > 0:
ap.play("Fall")
func crouch():
if is_crouching:
return
is_crouching = true
cshape.shape = crouching_cshape
cshape.position.y = -67
func stand():
if is_crouching ==false:
return
is_crouching = false
cshape.shape = standing_cshape
cshape.position.y = -75