Advertisement
Guest User

Create your first 2D game in Godot - C# version

a guest
Oct 18th, 2023
15,107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2. using Godot;
  3.  
  4. public partial class main_character : CharacterBody2D
  5. {
  6.     public const float Speed = 400.0f;
  7.     public const float JumpVelocity = -900.0f;
  8.  
  9.     private AnimatedSprite2D sprite2d;
  10.  
  11.     public override void _Ready()
  12.     {
  13.         sprite2d = GetNode<AnimatedSprite2D>("Sprite2D");
  14.         GD.Print(sprite2d);
  15.     }
  16.  
  17.     // Get the gravity from the project settings to be synced with RigidBody nodes.
  18.     public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
  19.  
  20.    
  21.  
  22.     public override void _PhysicsProcess(double delta)
  23.     {
  24.         Vector2 velocity = Velocity;
  25.  
  26.         // Animations
  27.         if (Math.Abs(velocity.X) > 1)
  28.             sprite2d.Animation = "running";
  29.         else
  30.             sprite2d.Animation = "default";
  31.  
  32.         // Add the gravity.
  33.         if (!IsOnFloor()) {
  34.             velocity.Y += gravity * (float)delta;
  35.             sprite2d.Animation = "jumping";
  36.         }
  37.  
  38.         // Handle Jump.
  39.         if (Input.IsActionJustPressed("jump") && IsOnFloor())
  40.             velocity.Y = JumpVelocity;
  41.  
  42.         // Get the input direction and handle the movement/deceleration.
  43.         // As good practice, you should replace UI actions with custom gameplay actions.
  44.         float direction = Input.GetAxis("left", "right");
  45.         if (direction != 0)
  46.         {
  47.             velocity.X = direction * Speed;
  48.         }
  49.         else
  50.         {
  51.             velocity.X = Mathf.MoveToward(Velocity.X, 0, 12);
  52.         }
  53.  
  54.         Velocity = velocity;
  55.         MoveAndSlide();
  56.  
  57.         // Flip the sprite based on the direction.
  58.         bool isLeft = velocity.X < 0;
  59.         sprite2d.FlipH = isLeft;
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement