- Edited
this is my code
extends CharacterBody3D
const SPEED = 5.0
const SPRINT_SPEED = 10.0 # Adjust as needed
const CROUCH_SPEED = 2.0 # Adjust as needed
const JUMP_VELOCITY = 4.5 # Increase the jump velocity for a more noticeable effect
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
# Crouch variables
var is_crouching = false
var original_scale = Vector3(1, 1, 1)
var crouched_scale = Vector3(1, 0.5, 1)
func _ready():
original_scale = scale
func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y -= gravity * delta
# Handle jump.
if is_on_floor() and Input.is_action_just_pressed("jump"):
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var input_dir = Input.get_vector("move_left", "move_right", "move_forward", "move_backward")
var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
if direction:
# Sprinting
if Input.is_action_pressed("sprinting"):
velocity.x = direction.x * SPRINT_SPEED
velocity.z = direction.z * SPRINT_SPEED
# Regular movement
else:
velocity.x = direction.x * SPEED
velocity.z = direction.z * SPEED
else:
velocity.x = 0
velocity.z = 0
# Crouch
if Input.is_action_pressed("crouching"):
crouch()
else:
stand()
move_and_slide() # Apply velocity without arguments
func crouch():
if not is_crouching:
is_crouching = true
scale = crouched_scale
position.y -= 1.0 # Adjust the position to maintain the same eye level
func stand():
if is_crouching:
is_crouching = false
scale = original_scale
position.y += 1.0 # Adjust the position when standing up