basic_movement.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // meta-description: Classic movement for gravity games (platformer, ...)
  2. using _BINDINGS_NAMESPACE_;
  3. using System;
  4. public partial class _CLASS_ : _BASE_
  5. {
  6. public const float Speed = 300.0f;
  7. public const float JumpVelocity = -400.0f;
  8. // Get the gravity from the project settings to be synced with RigidBody nodes.
  9. public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
  10. public override void _PhysicsProcess(double delta)
  11. {
  12. Vector2 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 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
  22. if (direction != Vector2.Zero)
  23. {
  24. velocity.x = direction.x * Speed;
  25. }
  26. else
  27. {
  28. velocity.x = Mathf.MoveToward(Velocity.x, 0, Speed);
  29. }
  30. Velocity = velocity;
  31. MoveAndSlide();
  32. }
  33. }