From ef93caeb133a652145082fb7fa75b8423fedacd0 Mon Sep 17 00:00:00 2001 From: Stanislav Balia Date: Sat, 30 Jul 2022 18:50:10 +0200 Subject: [PATCH] Add C# code examples on Listening to player input (#6009) --- .../step_by_step/scripting_player_input.rst | 57 ++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/getting_started/step_by_step/scripting_player_input.rst b/getting_started/step_by_step/scripting_player_input.rst index 61d072b9e..74b5f87cd 100644 --- a/getting_started/step_by_step/scripting_player_input.rst +++ b/getting_started/step_by_step/scripting_player_input.rst @@ -42,6 +42,20 @@ code below. rotation += angular_speed * direction * delta + .. code-tab:: csharp C# + + var direction = 0; + if (Input.IsActionPressed("ui_left")) + { + direction = -1; + } + if (Input.IsActionPressed("ui_right")) + { + direction = 1; + } + + Rotation += AngularSpeed * direction * delta; + Our ``direction`` local variable is a multiplier representing the direction in which the player wants to turn. A value of ``0`` means the player isn't pressing the left or the right arrow key. A value of ``1`` means the player wants to turn @@ -75,12 +89,20 @@ To only move when pressing a key, we need to modify the code that calculates the velocity. Replace the line starting with ``var velocity`` with the code below. .. tabs:: - .. code-tab:: gdscript GDScript + .. code-tab:: gdscript GDScript var velocity = Vector2.ZERO if Input.is_action_pressed("ui_up"): velocity = Vector2.UP.rotated(rotation) * speed + .. code-tab:: csharp C# + + var velocity = Vector2.Zero; + if (Input.IsActionPressed("ui_up")) + { + velocity = Vector2.Up.Rotated(Rotation) * Speed; + } + We initialize the ``velocity`` with a value of ``Vector2.ZERO``, another constant of the built-in ``Vector`` type representing a 2D vector of length 0. @@ -116,6 +138,39 @@ Here is the complete ``Sprite.gd`` file for reference. position += velocity * delta + .. code-tab:: csharp C# + + using Godot; + + public class Sprite : Godot.Sprite + { + private float Speed = 400; + private float AngularSpeed = Mathf.Pi; + + public override void _Process(float delta) + { + var direction = 0; + if (Input.IsActionPressed("ui_left")) + { + direction = -1; + } + if (Input.IsActionPressed("ui_right")) + { + direction = 1; + } + + Rotation += AngularSpeed * direction * delta; + + var velocity = Vector2.Zero; + if (Input.IsActionPressed("ui_up")) + { + velocity = Vector2.Up.Rotated(Rotation) * Speed; + } + + Position += velocity * delta; + } + } + If you run the scene, you should now be able to rotate with the left and right arrow keys and move forward by pressing :kbd:`Up`.