cubio.gd 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. extends CharacterBody3D
  2. const MAX_SPEED = 3.5
  3. const JUMP_SPEED = 6.5
  4. const ACCELERATION = 4
  5. const DECELERATION = 4
  6. @onready var camera = $Target/Camera3D
  7. @onready var gravity = -ProjectSettings.get_setting("physics/3d/default_gravity")
  8. @onready var start_position = position
  9. func _physics_process(delta):
  10. if Input.is_action_just_pressed(&"exit"):
  11. get_tree().quit()
  12. if Input.is_action_just_pressed(&"reset_position") or global_position.y < - 6:
  13. # Pressed the reset key or fell off the ground.
  14. position = start_position
  15. velocity = Vector3.ZERO
  16. var dir = Vector3()
  17. dir.x = Input.get_axis(&"move_left", &"move_right")
  18. dir.z = Input.get_axis(&"move_forward", &"move_back")
  19. # Get the camera's transform basis, but remove the X rotation such
  20. # that the Y axis is up and Z is horizontal.
  21. var cam_basis = camera.global_transform.basis
  22. cam_basis = cam_basis.rotated(cam_basis.x, -cam_basis.get_euler().x)
  23. dir = cam_basis * dir
  24. # Limit the input to a length of 1. length_squared is faster to check.
  25. if dir.length_squared() > 1:
  26. dir /= dir.length()
  27. # Apply gravity.
  28. velocity.y += delta * gravity
  29. # Using only the horizontal velocity, interpolate towards the input.
  30. var hvel = velocity
  31. hvel.y = 0
  32. var target = dir * MAX_SPEED
  33. var acceleration
  34. if dir.dot(hvel) > 0:
  35. acceleration = ACCELERATION
  36. else:
  37. acceleration = DECELERATION
  38. hvel = hvel.lerp(target, acceleration * delta)
  39. # Assign hvel's values back to velocity, and then move.
  40. velocity.x = hvel.x
  41. velocity.z = hvel.z
  42. # TODO: This information should be set to the CharacterBody properties instead of arguments: , Vector3.UP
  43. # TODO: Rename velocity to linear_velocity in the rest of the script.
  44. move_and_slide()
  45. # TODO: This information should be set to the CharacterBody properties instead of arguments.
  46. # Jumping code. is_on_floor() must come after move_and_slide().
  47. if is_on_floor() and Input.is_action_pressed(&"jump"):
  48. velocity.y = JUMP_SPEED
  49. func _on_tcube_body_entered(body):
  50. if body == self:
  51. get_node(^"WinText").show()