Wie kann ich erkennen ob 1 Meter vor der Kamera ein Hindernis ist?
extends CharacterBody3D
@onready var head = $SpringArm3D/Head
@onready var collision_shape = $CollisionShape3D
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
var speed = 4.0
var jump_speed = 6.0
var mouse_sensitivity = 0.002
var vertical_angle = 0.0
var is_crouching = false
var crouch_height = 0.5
var standing_height = 1.8
func _ready():
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
func get_input():
var input = Input.get_vector("move_left", "move_right", "move_forward", "move_backward")
var movement_dir = transform.basis * Vector3(input.x, 0, input.y)
velocity.x = movement_dir.x * speed
velocity.z = movement_dir.z * speed
if Input.is_action_just_pressed("crouch") and is_on_floor():
toggle_crouch()
if Input.is_action_just_pressed("Escape"):
if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
else:
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
if Input.is_action_pressed("jump") and is_on_floor():
velocity.y = jump_speed
func _process(delta):
check_collision()
func check_collision():
var space_state = get_world_3d().direct_space_state
var transform = global_transform
var query = PhysicsShapeQueryParameters3D.new()
query.shape = collision_shape.shape
query.transform = transform
#query.collide_with_areas = true # Nur Areas berücksichtigen
var results = space_state.intersect_shape(query)
for result in results:
if result.collider:
print("Kollision mit:", result.collider.name)
func _physics_process(delta):
velocity.y += -gravity * delta
get_input()
move_and_slide()
func toggle_crouch():
if is_crouching:
is_crouching = false
collision_shape.shape.height = standing_height
head.position.y = standing_height # Kamera anpassen
else:
is_crouching = true
collision_shape.shape.height = crouch_height
head.position.y = crouch_height # Kamera anpassen
func _unhandled_input(event):
if event is InputEventMouseMotion:
# Horizontale Charakterrotation (um die y-Achse)
rotate_y(-event.relative.x * mouse_sensitivity)
# Vertikale Kamerarotation (um die x-Achse des SpringArm3D)
vertical_angle -= event.relative.y * mouse_sensitivity
vertical_angle = clamp(vertical_angle, -PI / 2, PI / 2) # Begrenzung der vertikalen Rotation auf +-90°
head.rotation.x = vertical_angle