rigidbody_ground_check.gd 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. extends RigidBody3D
  2. @onready var _forward = -transform.basis.z
  3. @onready var _collision_shape = $CollisionShape
  4. @onready var _material = $CollisionShape/MeshInstance3D.get_active_material(0)
  5. var _dir = 1.0
  6. var _distance = 10.0
  7. var _walk_spd = 100.0
  8. var _acceleration = 22.0
  9. var _is_on_floor = false
  10. func _ready():
  11. if not _material:
  12. _material = StandardMaterial3D.new()
  13. $CollisionShape/MeshInstance3D.set_surface_override_material(0, _material)
  14. func _process(_delta):
  15. if _is_on_floor:
  16. _material.albedo_color = Color.WHITE
  17. else:
  18. _material.albedo_color = Color.RED
  19. func _integrate_forces(state):
  20. var delta = state.step
  21. var velocity = (_forward * _dir * _walk_spd * delta) + (state.linear_velocity * Vector3.UP)
  22. state.linear_velocity = state.linear_velocity.move_toward(velocity, _acceleration * delta)
  23. if state.transform.origin.z < -_distance:
  24. _dir = -1
  25. if state.transform.origin.z > _distance:
  26. _dir = 1
  27. ground_check()
  28. func ground_check():
  29. var space_state = get_world_3d().direct_space_state
  30. var shape = PhysicsShapeQueryParameters3D.new()
  31. shape.transform = _collision_shape.global_transform
  32. shape.shape_rid = _collision_shape.shape.get_rid()
  33. shape.collision_mask = 2
  34. var result = space_state.get_rest_info(shape)
  35. if result:
  36. _is_on_floor = true
  37. else:
  38. _is_on_floor = false