EdgeLordKirito

Godot First 2d

Jan 11th, 2024 (edited)
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | Source Code | 0 0
  1. using Godot;
  2. using System;
  3.  
  4. public partial class Player : Area2D
  5. {
  6.     [Export]
  7.     public int Speed { get; set; }
  8.  
  9.     public Vector2 ScreenSize;
  10.  
  11.     // Called when the node enters the scene tree for the first time.
  12.     public override void _Ready()
  13.     {
  14.         ScreenSize = GetViewportRect().Size;
  15.     }
  16.  
  17.     // Called every frame. 'delta' is the elapsed time since the previous frame.
  18.     public override void _Process(double delta)
  19.     {
  20.         Vector2 velocity = Vector2.Zero;
  21.  
  22.         if (Input.IsActionPressed("move_right"))
  23.         {
  24.             velocity.X += 1;
  25.             GD.Print("right");
  26.         }
  27.        
  28.         if (Input.IsActionPressed("move_left"))
  29.         {
  30.             velocity.X -= 1;
  31.             GD.Print("left");
  32.  
  33.         }
  34.  
  35.         if (Input.IsActionPressed("move_down"))
  36.         {
  37.             velocity.Y += 1;
  38.             GD.Print("down");
  39.         }
  40.  
  41.         if (Input.IsActionPressed("move_up"))
  42.         {
  43.             velocity.Y -= 1;
  44.             GD.Print("up");
  45.         }
  46.  
  47.         GD.Print($"X: {Position.X} Y: {Position.Y}");
  48.  
  49.         var sprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
  50.  
  51.         if (velocity.Length() > 0)
  52.         {
  53.             velocity = velocity.Normalized() * Speed;
  54.             sprite.Play();
  55.         }
  56.         else
  57.         {
  58.             sprite.Stop();
  59.         }
  60.  
  61.         Position += velocity * (float)delta;
  62.         Position = new Vector2(
  63.             x: Mathf.Clamp(Position.X, 0, ScreenSize.X),
  64.             y: Mathf.Clamp(Position.Y, 0, ScreenSize.Y)
  65.             );
  66.  
  67.         if (velocity.X != 0)
  68.         {
  69.             sprite.Animation = "walk";
  70.             sprite.FlipV = false;
  71.  
  72.             sprite.FlipH = velocity.X < 0;
  73.         }
  74.         else if (velocity.Y != 0)
  75.         {
  76.             sprite.Animation = "up";
  77.             sprite.FlipV = velocity.Y > 0;
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment