Add C# code examples on Listening to player input (#6009)

This commit is contained in:
Stanislav Balia
2022-07-30 18:50:10 +02:00
committed by GitHub
parent 55d3093715
commit 96475315a9

View File

@@ -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 ``Sprite2D.gd`` file for reference.
position += velocity * delta
.. code-tab:: csharp C#
using Godot;
public class Sprite : Godot.Sprite2D
{
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`.