PlayerMath25D.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Godot;
  2. #if REAL_T_IS_DOUBLE
  3. using real_t = System.Double;
  4. #else
  5. using real_t = System.Single;
  6. #endif
  7. /// <summary>
  8. /// Handles Player-specific behavior like moving. We calculate such things with CharacterBody3D.
  9. /// </summary>
  10. public partial class PlayerMath25D : CharacterBody3D
  11. {
  12. private Node25D _parent;
  13. public real_t verticalSpeed = 0;
  14. public bool isometricControls = true;
  15. public override void _Ready()
  16. {
  17. _parent = GetParent<Node25D>();
  18. }
  19. public override void _Process(real_t delta)
  20. {
  21. if (Input.IsActionPressed("exit"))
  22. {
  23. GetTree().Quit();
  24. }
  25. if (Input.IsActionJustPressed("view_cube_demo"))
  26. {
  27. GetTree().ChangeScene("res://assets/cube/cube.tscn");
  28. return;
  29. }
  30. if (Input.IsActionJustPressed("toggle_isometric_controls"))
  31. {
  32. isometricControls = !isometricControls;
  33. }
  34. if (Input.IsActionPressed("reset_position"))
  35. {
  36. Transform = new Transform3D(Basis.Identity, Vector3.Up * 10);
  37. verticalSpeed = 0;
  38. }
  39. else
  40. {
  41. HorizontalMovement(delta);
  42. VerticalMovement(delta);
  43. }
  44. }
  45. /// <summary>
  46. /// Checks WASD and Shift for horizontal movement via MoveAndSlide.
  47. /// </summary>
  48. private void HorizontalMovement(real_t delta)
  49. {
  50. Vector3 localX = Vector3.Right;
  51. Vector3 localZ = Vector3.Back;
  52. if (isometricControls && _parent.Basis25D.x.IsEqualApprox(Basis25D.Isometric.x * Node25D.SCALE))
  53. {
  54. localX = new Vector3(0.70710678118f, 0, -0.70710678118f);
  55. localZ = new Vector3(0.70710678118f, 0, 0.70710678118f);
  56. }
  57. // Gather player input and add directional movement to a Vector3 variable.
  58. Vector2 movementVec2 = Input.GetVector("move_left", "move_right", "move_forward", "move_back");
  59. Vector3 moveDir = localX * movementVec2.x + localZ * movementVec2.y;
  60. moveDir = moveDir * delta * 600;
  61. if (Input.IsActionPressed("movement_modifier"))
  62. {
  63. moveDir /= 2;
  64. }
  65. MoveAndSlide(moveDir);
  66. }
  67. /// <summary>
  68. /// Checks Jump and applies gravity and vertical speed via MoveAndCollide.
  69. /// </summary>
  70. /// <param name="delta">Time delta since last call</param>
  71. private void VerticalMovement(real_t delta)
  72. {
  73. if (Input.IsActionJustPressed("jump"))
  74. {
  75. verticalSpeed = 1.25f;
  76. }
  77. verticalSpeed -= delta * 5; // Gravity
  78. var k = MoveAndCollide(Vector3.Up * verticalSpeed);
  79. if (k != null)
  80. {
  81. verticalSpeed = 0;
  82. }
  83. }
  84. }