basic_movement.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // meta-description: Classic movement for gravity games (FPS, TPS, ...)
  2. using _BINDINGS_NAMESPACE_;
  3. using System;
  4. public partial class _CLASS_ : _BASE_
  5. {
  6. public const float Speed = 5.0f;
  7. public const float JumpVelocity = 4.5f;
  8. // Get the gravity from the project settings to be synced with RigidBody nodes.
  9. public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
  10. public override void _PhysicsProcess(double delta)
  11. {
  12. Vector3 velocity = Velocity;
  13. // Add the gravity.
  14. if (!IsOnFloor())
  15. velocity.y -= gravity * (float)delta;
  16. // Handle Jump.
  17. if (Input.IsActionJustPressed("ui_accept") && IsOnFloor())
  18. velocity.y = JumpVelocity;
  19. // Get the input direction and handle the movement/deceleration.
  20. // As good practice, you should replace UI actions with custom gameplay actions.
  21. Vector2 inputDir = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
  22. Vector3 direction = (Transform.basis * new Vector3(inputDir.x, 0, inputDir.y)).Normalized();
  23. if (direction != Vector3.Zero)
  24. {
  25. velocity.x = direction.x * Speed;
  26. velocity.z = direction.z * Speed;
  27. }
  28. else
  29. {
  30. velocity.x = Mathf.MoveToward(Velocity.x, 0, Speed);
  31. velocity.z = Mathf.MoveToward(Velocity.z, 0, Speed);
  32. }
  33. Velocity = velocity;
  34. MoveAndSlide();
  35. }
  36. }