Ver código fonte

Merge pull request #2198 from neikeq/csharp-fixes

Fixes and improvements of C# code examples
Rémi Verschelde 6 anos atrás
pai
commit
c20387fd1e

+ 2 - 2
getting_started/scripting/c_sharp/c_sharp_features.rst

@@ -13,8 +13,8 @@ C# is a statically typed language. Therefore, you can't do the following:
 
 .. code-block:: csharp
 
-    var mySprite = GetNode("MySprite")
-    mySprite.SetFrame(0)
+    var mySprite = GetNode("MySprite");
+    mySprite.SetFrame(0);
 
 The method ``GetNode()`` returns a ``Node`` instance.
 You must explicitly convert it to the desired derived type, ``Sprite`` in this case.

+ 5 - 6
getting_started/step_by_step/resources.rst

@@ -291,8 +291,8 @@ Let's see some examples.
 
                 public override void _Ready()
                 {
-                    if (Stats != null && Stats is BotStats) {
-                        GD.print((Stats as BotStats).Health); // Prints '10'.
+                    if (Stats != null && Stats is BotStats botStats) {
+                        GD.Print(botStats.Health); // Prints '10'.
                     }
                 }
             }
@@ -338,7 +338,7 @@ Let's see some examples.
             {
                 _stats["GodotBot"] = new BotStats(10); // Creates instance with 10 health.
                 _stats["DifferentBot"] = new BotStats(20); // A different one with 20 health.
-                Godot.print(_stats);
+                GD.Print(_stats);
             }
         }
 
@@ -384,7 +384,6 @@ Let's see some examples.
 
         public class MyNode : Node
         {
-
             public class MyResource : Resource
             {
                 [Export]
@@ -393,9 +392,9 @@ Let's see some examples.
 
             public override void _Ready()
             {
-                MyResource res = new MyResource();
+                var res = new MyResource();
 
                 // This will NOT serialize the 'Value' property.
-                ResourceSaver.save("res://MyRes.tres", res);
+                ResourceSaver.Save("res://MyRes.tres", res);
             }
         }

+ 1 - 1
getting_started/step_by_step/scene_tree.rst

@@ -175,7 +175,7 @@ function
 
     public void _MyLevelWasCompleted()
     {
-        PackedScene nextScene = ResourceLoader.load("res://levels/level2.tscn") as PackedScene;
+        var nextScene = (PackedScene)ResourceLoader.Load("res://levels/level2.tscn");
         GetTree().ChangeSceneTo(nextScene);
     }
 

+ 5 - 2
getting_started/step_by_step/signals.rst

@@ -274,9 +274,12 @@ Here is the code for the player using signals to emit the bullet:
 
         public override void _Input(InputEvent event)
         {
-            if (input is InputEventMouseButton && Input.IsMouseButtonPressed((int)ButtonList.Left))
+            if (input is InputEventMouseButton mouseButton)
             {
-                EmitSignal(nameof(Shoot), _bullet, Rotation, Position);
+                if (mouseButton.ButtonIndex == (int)ButtonList.Left && mouseButton.Pressed)
+                {
+                    EmitSignal(nameof(Shoot), _bullet, Rotation, Position);
+                }
             }
         }
 

+ 16 - 13
getting_started/workflow/best_practices/data_preferences.rst

@@ -17,7 +17,7 @@ Y or Z? This article covers a variety of topics related to these dilemmas.
 
   "As the size of a problem domain increases, the runtime length of the
   algorithm..."
-  
+
   - Constant-time, ``O(1)``: "...does not increase."
   - Logarithmic-time, ``O(log n)``: "...increases at a slow rate."
   - Linear-time, ``O(n)``: "...increases at the same rate."
@@ -25,7 +25,7 @@ Y or Z? This article covers a variety of topics related to these dilemmas.
 
   Imagine if one had to process 3 million data points within a single frame. It
   would be impossible to craft the feature with a linear-time algorithm since
-  the sheer size of the data would increase the runtime far beyond the time alotted. 
+  the sheer size of the data would increase the runtime far beyond the time alotted.
   In comparison, using a constant-time algorithm could handle the operation without
   issue.
 
@@ -183,18 +183,18 @@ looking up data.
 
   When developers mention how slow the scripting API is, it is this chain
   of queries they refer to. Compared to compiled C++ code where the
-  application knows exactly where to go to find anything, it is inevitable 
+  application knows exactly where to go to find anything, it is inevitable
   that scripting API operations will take much longer. They must locate the
   source of any relevant data before they can attempt to access it.
 
   The reason GDScript is slow is because every operation it performs passes
   through this system.
-  
+
   C# can process some content at higher speeds via more optimized bytecode.
   But, if the C# script calls into an engine class'
   content or if the script tries to access something external to it, it will
   go through this pipeline.
-  
+
   NativeScript C++ goes even further and keeps everything internal by default.
   Calls into external structures will go through the scripting API. In
   NativeScript C++, registering methods to expose them to the scripting API is
@@ -247,18 +247,21 @@ tree structures.
   .. code-tab:: csharp
 
     // Can decide whether to expose getters/setters for properties later
-    public class TreeNode : public Object {
-
+    public class TreeNode : Object
+    {
         private TreeNode _parent = null;
 
         private object[] _children = new object[0];
 
-        // Not sure if this should be a destructor or a notification
-        public void ~TreeNode() {
-            foreach (object child in _children) {
-                TreeNode node = child as TreeNode;
-                if (node != null) {
-                    node.Free();
+        public override void Notification(int what)
+        {
+            if (what == NotificationPredelete)
+            {
+                foreach (object child in _children)
+                {
+                    TreeNode node = child as TreeNode;
+                    if (node != null)
+                        node.Free();
                 }
             }
         }

+ 13 - 11
getting_started/workflow/best_practices/godot_interfaces.rst

@@ -76,28 +76,29 @@ access.
         // No "preload" loads during scene load exists in C#.
 
         // Initialize with a value. Editable at runtime.
-        public Script MyScript = GD.Load("MyScript.cs");
+        public Script MyScript = GD.Load<Script>("MyScript.cs");
 
-        // Initialize with same value. Value locked.
-        public const Script MyConstScript = GD.Load("MyScript.cs");
+        // Initialize with same value. Value cannot be changed.
+        public readonly Script MyConstScript = GD.Load<Script>("MyScript.cs");
 
-        // Like 'const' due to inaccessible setter.
+        // Like 'readonly' due to inaccessible setter.
         // But, value can be set during constructor, i.e. MyType().
-        public Script Library { get; } = GD.Load("res://addons/plugin/library.gd") as Script;
+        public Script Library { get; } = GD.Load<Script>("res://addons/plugin/library.gd");
 
         // If need a "const [Export]" (which doesn't exist), use a
         // conditional setter for a tool script that checks if it's executing
         // in the editor.
+        private PackedScene _enemyScn;
+
         [Export]
         public PackedScene EnemyScn
         {
-            get;
-
+            get { return _enemyScn; }
             set
             {
                 if (Engine.IsEditorHint())
                 {
-                    EnemyScn = value;
+                    _enemyScn = value;
                 }
             }
         };
@@ -106,7 +107,7 @@ access.
         public String _GetConfigurationWarning()
         {
             if (EnemyScn == null)
-                return "Must initialize property 'const_script'.";
+                return "Must initialize property 'EnemyScn'.";
             return "";
         }
     }
@@ -204,7 +205,8 @@ Nodes likewise have an alternative access point: the SceneTree.
         // Pro: node makes no requirements of its external structure.
         //      'prop' can come from anywhere.
         public object Prop;
-        public void CallMeAfterPropIsInitializedByParent() {
+        public void CallMeAfterPropIsInitializedByParent()
+        {
             // Validate prop in one of three ways
 
             // Fail with no notification
@@ -245,7 +247,7 @@ It instead checks that the object **implements** the individual method.
 
 For example, the :ref:`CanvasItem <class_CanvasItem>` class has a ``visible``
 property. All properties exposed to the scripting API are in fact a setter and
-getter pair bound to a name. If one tried to access 
+getter pair bound to a name. If one tried to access
 :ref:`CanvasItem.visible <class_CanvasItem_property_visible>`, then Godot would do the
 following checks, in order:
 

+ 41 - 30
getting_started/workflow/best_practices/godot_notifications.rst

@@ -114,7 +114,7 @@ deltatime methods as needed.
 
     # Called every frame, even when the engine detects no input.
     func _process(delta):
-        if Input.action_just_pressed("ui_select"):
+        if Input.is_action_just_pressed("ui_select"):
             print(delta)
 
     # Called during every input event.
@@ -126,20 +126,24 @@ deltatime methods as needed.
 
   .. code-tab:: csharp
 
-    public class MyNode : public Node {
+    public class MyNode : Node
+    {
 
         // Called every frame, even when the engine detects no input.
-        public void _Process(float delta) {
-            if (GD.Input.ActionJustPressed("UiSelect")) {
-                GD.Print(string(delta));
-            }
+        public void _Process(float delta)
+        {
+            if (Input.IsActionJustPressed("ui_select"))
+                GD.Print(delta);
         }
 
         // Called during every input event. Equally true for _input().
-        public void _UnhandledInput(InputEvent event) {
-            switch (event.GetClass()) {
-                case "InputEventAction":
-                    GD.Print(string(GetProcessDeltaTime());
+        public void _UnhandledInput(InputEvent event)
+        {
+            switch (event)
+            {
+                case InputEventKey keyEvent:
+                    if (Input.IsActionJustPressed("ui_accept"))
+                        GD.Print(GetProcessDeltaTime());
                     break;
                 default:
                     break;
@@ -180,24 +184,27 @@ instantiation:
 
   .. code-tab:: csharp
 
-    // "one" is an "initialized value". These DO NOT trigger the setter.
-    // If one set the value as "two" from the Inspector, this would be an
-    // "exported value". These DO trigger the setter.
-    [Export]
-    public string Test = "one"
+    public class MyNode : Node
     {
-        get;
-        set
+        private string _test = "one";
+
+        // Changing the value from the inspector does trigger the setter in C#.
+        [Export]
+        public string Test
         {
-            Test = value;
-            GD.Print("Setting: " + Test);
+            get { return _test; }
+            set
+            {
+                _test = value;
+                GD.Print("Setting: " + _test);
+            }
         }
-    }
 
-    public void _Init() {
-        // "three" is an "init assignment value".
-        // These DO (NOT?) trigger the setter.
-        Test = "three";
+        public MyNode()
+        {
+            // Triggers the setter as well
+            Test = "three";
+        }
     }
 
 When instantiating a scene, property values will set up according to the
@@ -260,16 +267,19 @@ nodes that one might create at runtime.
 
   .. code-tab:: csharp
 
-    public class MyNode extends Node {
-
+    public class MyNode : Node
+    {
         public Node ParentCache = null;
 
-        public void ConnectionCheck() {
+        public void ConnectionCheck()
+        {
             return ParentCache.HasUserSignal("InteractedWith");
         }
 
-        public void _Notification(int What) {
-            switch (What) {
+        public void _Notification(int what)
+        {
+            switch (what)
+            {
                 case NOTIFICATION_PARENTED:
                     ParentCache = GetParent();
                     if (ConnectionCheck())
@@ -282,7 +292,8 @@ nodes that one might create at runtime.
             }
         }
 
-        public void OnParentInteractedWith() {
+        public void OnParentInteractedWith()
+        {
             GD.Print("I'm reacting to my parent's interaction!");
         }
     }

+ 10 - 9
getting_started/workflow/best_practices/logic_preferences.rst

@@ -32,7 +32,7 @@ either? Let's see an example:
 
     # (note how constant scripts/scenes have a diferent naming scheme than
     # their property variants).
-  
+
     # This value is a constant, so it spawns when the Script object loads.
     # The script is preloading the value. The advantage here is that the editor
     # can offer autocompletion since it must be a static path.
@@ -43,15 +43,15 @@ either? Let's see an example:
     #    property rather than a constant, the object won't copy the preloaded
     #    PackedScene resource into the property until the script instantiates
     #    with .new().
-    # 
+    #
     # 2. The preloaded value is inaccessible from the Script object alone. As
     #    such, preloading the value here actually does not benefit anyone.
-    # 
-    # 3. Because the user exports the value, if this script stored on 
+    #
+    # 3. Because the user exports the value, if this script stored on
     #    a node in a scene file, the scene instantation code will overwrite the
     #    preloaded initial value anyway (wasting it). It's usually better to
     #    provide null, empty, or otherwise invalid default values for exports.
-    # 
+    #
     # 4. It is when one instantiates this script on its own with .new() that
     #    one will load "office.tscn" rather than the exported value.
     export(PackedScene) var a_building = preload("office.tscn")
@@ -71,14 +71,15 @@ either? Let's see an example:
     using Godot;
 
     // C# and other languages have no concept of "preloading".
-    public class MyBuildings : Node {
-    
+    public class MyBuildings : Node
+    {
         //This is a read-only field, it can only be assigned when it's declared or during a constructor
         public readonly PackedScene Building = ResourceLoader.Load<PackedScene>("res://building.tscn");
-        
+
         public PackedScene ABuilding;
 
-        public override void _Ready() {
+        public override void _Ready()
+        {
             // Can assign the value during initialization
             ABuilding = GD.Load<PackedScene>("res://office.tscn");
         }

+ 17 - 13
getting_started/workflow/best_practices/scene_organization.rst

@@ -178,23 +178,27 @@ in another context without any extra changes to its API.
     .. code-tab:: csharp
 
       // Parent
-      GetNode("Left").Target = GetNode("Right/Receiver");
+      GetNode<Left>("Left").Target = GetNode("Right/Receiver");
 
-      // Left
-      public Node Target = null;
-
-      public void Execute()
+      public class Left : Node
       {
-          // Do something with 'Target'.
-      }
+          public Node Target = null;
 
-      // Right
-      public Node Receiver = null;
+          public void Execute()
+          {
+              // Do something with 'Target'.
+          }
+      }
 
-      public Right()
+      public class Right : Node
       {
-          Receiver = ResourceLoader.load("Receiver.cs").new();
-          AddChild(Receiver);
+          public Node Receiver = null;
+
+          public Right()
+          {
+              Receiver = ResourceLoader.Load<Script>("Receiver.cs").New();
+              AddChild(Receiver);
+          }
       }
 
   The same principles also apply to non-Node objects that maintain dependencies
@@ -322,7 +326,7 @@ own place in the hierachy as a sibling or some other relation.
 
   1. A reliable third party, likely a parent node, to mediate the assignment.
   2. A group, to easily pull a reference to the desired node (assuming there
-     will only ever be one of the targets). 
+     will only ever be one of the targets).
 
   When should one do this? Well, it's up to them to decide. The dilemma
   arises when one must micro-manage when a node must move around the SceneTree

+ 6 - 6
getting_started/workflow/best_practices/scenes_versus_scripts.rst

@@ -17,7 +17,7 @@ Anonymous types
 
 It *is* possible to completely define a scenes' contents using a script alone.
 This is, in essence, what the Godot Editor does, only in the C++ constructor
-of its objects. 
+of its objects.
 
 But, choosing which one to use can be a dilemma. Creating script instances
 is identical to creating in-engine classes whereas handling scenes requires
@@ -40,8 +40,8 @@ a change in API:
 
         public class Game : Node
         {
-            public const Script MyNodeScr = ResourceLoader.load("MyNode.cs") as Script;
-            public const PackedScene MySceneScn= ResourceLoader.load("MyScene.tscn") as PackedScene;
+            public readonly Script MyNodeScr = (Script)ResourceLoader.Load("MyNode.cs");
+            public readonly PackedScene MySceneScn = (PackedScene)ResourceLoader.load("MyScene.tscn");
             public Node ANode;
             public Node MyNode;
             public Node MyScene;
@@ -51,8 +51,8 @@ a change in API:
             {
                 ANode = new Node();
                 MyNode = new MyNode(); // Same syntax
-                MyScene = MySceneScn.instance(); // different syntax
-                MyInheritedScene = MySceneScn.instance(PackedScene.GEN_EDIT_STATE_MAIN); // Create scene inheriting from MyScene
+                MyScene = MySceneScn.Instance(); // Different. Instantiated from a PackedScene
+                MyInheritedScene = MySceneScn.Instance(PackedScene.GenEditState.Main); // Create scene inheriting from MyScene
             }
         }
 
@@ -105,7 +105,7 @@ There are two systems for registering types...
 
    - Editor has no type-awareness of the script or its relationship
      to other engine types or scripts.
-     
+
    - Allows users to define an icon.
 
    - Works for all scripting languages because it deals with Script resources in abstract.

+ 5 - 4
getting_started/workflow/best_practices/what_are_godot_classes.rst

@@ -59,10 +59,10 @@ let's see a simple example of creating a single Node as a child.
 
 .. tabs::
   .. code-tab:: gdscript GDScript
-    
+
     # main.gd
     extends Node
-    
+
     var child # define a variable to store a reference to the child
 
     func _init():
@@ -78,7 +78,8 @@ let's see a simple example of creating a single Node as a child.
     using System;
     using Godot;
 
-    namespace ExampleProject {
+    namespace ExampleProject
+    {
         public class Main : Resource
         {
             public Node Child { get; set; }
@@ -87,7 +88,7 @@ let's see a simple example of creating a single Node as a child.
             {
                 Child = new Node(); // Construct the child.
                 Child.Name = "Child"; // Change its name.
-                Child.Script = ResourceLoader.load("child.gd") as Script; // Give it custom features.
+                Child.Script = (Script)ResourceLoader.Load("child.gd"); // Give it custom features.
                 Child.Owner = this; // Serialize this node if this is saved.
                 AddChild(Child); // Add "Child" as a child of this.
             }

+ 1 - 1
getting_started/workflow/export/exporting_pcks.rst

@@ -109,7 +109,7 @@ file in the directory of the games executable. The PCK file contains a
     {
         ProjectSettings.LoadResourcePack("res://mod.pck");
         // Now one can use the assets as if they had them in the project from the start
-        var importedScene = ResourceLoader.Load("res://mod_scene.tscn") as PackedScene;
+        var importedScene = (PackedScene)ResourceLoader.Load("res://mod_scene.tscn");
     }
 
 .. warning::

+ 13 - 20
tutorials/2d/2d_movement.rst

@@ -75,22 +75,19 @@ Add a script to the kinematic body and add the following code:
         public void GetInput()
         {
             velocity = new Vector2();
+
             if (Input.IsActionPressed("right"))
-            {
                 velocity.x += 1;
-            }
+
             if (Input.IsActionPressed("left"))
-            {
                 velocity.x -= 1;
-            }
+
             if (Input.IsActionPressed("down"))
-            {
                 velocity.y += 1;
-            }
+
             if (Input.IsActionPressed("up"))
-            {
                 velocity.y -= 1;
-            }
+
             velocity = velocity.Normalized() * Speed;
         }
 
@@ -166,22 +163,19 @@ while up/down moves it forward or backward in whatever direction it's facing.
         {
             rotationDir = 0;
             velocity = new Vector2();
+
             if (Input.IsActionPressed("right"))
-            {
                 rotationDir += 1;
-            }
+
             if (Input.IsActionPressed("left"))
-            {
                 rotationDir -= 1;
-            }
+
             if (Input.IsActionPressed("down"))
-            {
                 velocity = new Vector2(-Speed, 0).Rotated(Rotation);
-            }
+
             if (Input.IsActionPressed("up"))
-            {
                 velocity = new Vector2(Speed, 0).Rotated(Rotation);
-            }
+
             velocity = velocity.Normalized() * Speed;
         }
 
@@ -247,14 +241,13 @@ is set by the mouse position instead of the keyboard. The character will always
         {
             LookAt(GetGlobalMousePosition());
             velocity = new Vector2();
+
             if (Input.IsActionPressed("down"))
-            {
                 velocity = new Vector2(-Speed, 0).Rotated(Rotation);
-            }
+
             if (Input.IsActionPressed("up"))
-            {
                 velocity = new Vector2(Speed, 0).Rotated(Rotation);
-            }
+
             velocity = velocity.Normalized() * Speed;
         }
 

+ 3 - 3
tutorials/2d/custom_drawing_in_2d.rst

@@ -26,7 +26,7 @@ examples why:
    tetris board). The tetris example uses a custom draw function to draw
    the blocks.
 -  Drawing a large number of simple objects. Custom drawing avoids the
-   overhead of using nodes which makes it less memory intensive and 
+   overhead of using nodes which makes it less memory intensive and
    potentially faster.
 -  Making a custom UI control. There are plenty of controls available,
    but it's easy to run into the need to make a new, custom one.
@@ -130,12 +130,12 @@ call ``update()`` from the ``_process()`` callback, like this:
 
     public class CustomNode2D : Node2D
     {
-        public override _Draw()
+        public override void _Draw()
         {
             // Your draw commands here
         }
 
-        public override _Process(delta)
+        public override void _Process(float delta)
         {
             Update();
         }

+ 2 - 4
tutorials/3d/using_transforms.rst

@@ -295,9 +295,8 @@ Jump:
 
     // Keep in mind Y is up-axis
     if (Input.IsActionJustPressed("jump"))
-    {
         velocity.y = JumpSpeed;
-    }
+
     velocity = MoveAndSlide(velocity);
 
 All common behaviors and logic can be done with just vectors.
@@ -335,8 +334,7 @@ Example of looking around, FPS style:
 
     public override void _Input(InputEvent @event)
     {
-        var mouseMotion = @event as InputEventMouseMotion;
-        if (mouseMotion != null)
+        if (mouseMotion is InputEventMouseMotion mouseMotion)
         {
             // modify accumulated mouse rotation
             _rotationX += mouseMotion.Relative.x * LookAroundSpeed;

+ 1 - 1
tutorials/animation/animation_tree.rst

@@ -249,7 +249,7 @@ object from the ``AnimationTree`` node (it is exported as a property).
 
  .. code-tab:: csharp
 
-    AnimationNodeStateMachinePlayback stateMachine = animTree.Get("parameters/StateMachine/playback") as AnimationNodeStateMachinePlayback;
+    AnimationNodeStateMachinePlayback stateMachine = (AnimationNodeStateMachinePlayback)animTree.Get("parameters/StateMachine/playback");
 
 Once retrieved, it can be used by calling one of the many functions it offers:
 

+ 4 - 18
tutorials/gui/custom_gui_controls.rst

@@ -55,7 +55,7 @@ exists. Example
 
     public override void _Draw()
     {
-        if(HasFocus())
+        if (HasFocus())
         {
             DrawSelected()
         }
@@ -142,25 +142,11 @@ Simply override it in your control. No processing needs to be set.
 
  .. code-tab:: csharp
 
-    public override void _GuiInput(InputEvent @event)
-    {
-        var mouseButtonEvent = @event as InputEventMouseButton;
-        if (mouseButtonEvent != null)
-        {
-            if (mouseButtonEvent.ButtonIndex == (int)ButtonList.Left && mouseButtonEvent.Pressed)
-            {
-                GD.Print("Left mouse button was pressed!");
-            }
-        }
-    }
-
-    // or alternatively when using C# 7 or greater we can use pattern matching
     public override void _GuiInput(InputEvent @event)
     {
         if (@event is InputEventMouseButton mbe && mbe.ButtonIndex == (int)ButtonList.Left && mbe.Pressed)
-            {
-                GD.Print("Left mouse button was pressed!");
-            }
+        {
+            GD.Print("Left mouse button was pressed!");
         }
     }
 
@@ -203,7 +189,7 @@ exists, but which can be checked with the _notification callback:
 
     public override void _Notification(int what)
     {
-        switch(what)
+        switch (what)
         {
             case NotificationMouseEnter:
                 // Mouse entered the area of this control.

+ 6 - 6
tutorials/misc/change_scenes_manually.rst

@@ -25,7 +25,7 @@ scenes which one instances and adds to the tree at runtime:
 
     public MyClass()
     {
-        simultaneousScene = ResourceLoader.load("res://levels/level2.tscn") as PackedScene;
+        simultaneousScene = (PackedScene)ResourceLoader.Load("res://levels/level2.tscn");
     }
 
     public void _AddASceneManually()
@@ -49,7 +49,7 @@ access and integrity.
    ``get_node("/root/Main").free()`` to delete the whole scene.
 
     - Unloads memory.
-    
+
         - Pro: RAM is no longer dragging the dead weight.
 
         - Con: Returning to that scene is now more expensive since it must be
@@ -90,11 +90,11 @@ access and integrity.
           keep updated any data within it that relies on delta time or frame
           data.
 
-        - Pro: Nodes are still members of groups (since groups belong to the 
+        - Pro: Nodes are still members of groups (since groups belong to the
           :ref:`SceneTree <class_SceneTree>`).
 
         - Con: The CPU's attention is now divided between both scenes. Too much
-          load could result in low frame rates. One should be sure to test 
+          load could result in low frame rates. One should be sure to test
           performance as they go to ensure the target platform can support the
           load they are giving it.
 
@@ -107,7 +107,7 @@ access and integrity.
 
     - Processing stops (similar pros/cons as with deleting it completely).
 
-    - Pro: This variation of "hiding" it is much easier to show/hide. Rather 
+    - Pro: This variation of "hiding" it is much easier to show/hide. Rather
       than potentially keeping track of multiple changes to the scene, one
       must only call the one method add/remove_child pair of methods. It is
       similar to disabling game objects in other engines.
@@ -136,5 +136,5 @@ cases where the intent is to render different content in different parts of the
 screen. Minimaps and split-screen multiplayer are good examples.
 
 Each option will have cases where it is best appropriate, so one must
-examine the effects of each and determine what path best fits 
+examine the effects of each and determine what path best fits
 their unique situation.

+ 2 - 2
tutorials/misc/pausing_games.rst

@@ -94,7 +94,7 @@ enable the pause and show the pause screen.
     public void _on_pause_button_pressed()
     {
         GetTree().Paused = true;
-        ((Control)GetNode("pause_popup")).Show();
+        GetNode<Control>("pause_popup").Show();
     }
 
 To remove the pause, do the opposite when the pause screen is
@@ -111,7 +111,7 @@ closed:
 
     public void _on_pause_popup_close_pressed()
     {
-        ((Control)GetNode("pause_popup")).Hide();
+        GetNode<Control>("pause_popup").Hide();
         GetTree().Paused = false;
     }
 

+ 4 - 6
tutorials/physics/kinematic_character_2d.rst

@@ -69,7 +69,6 @@ or lose precision if the frame rate is too high or too low.
 
     public class PhysicsScript : KinematicBody2D
     {
-
         public override void _PhysicsProcess(float delta)
         {
         }
@@ -135,11 +134,10 @@ So, let's move our sprite downwards until it hits the floor:
 
     public class PhysicsScript : KinematicBody2D
     {
-
         public override void _PhysicsProcess(float delta)
         {
             // Move down 1 pixel per physics frame
-            MoveAndCollide(new Vector2 (0,1));
+            MoveAndCollide(new Vector2(0, 1));
         }
     }
 
@@ -222,7 +220,7 @@ This adds simple walking support by pressing left and right:
     public class PhysicsScript : KinematicBody2D
     {
         const float gravity = 200.0f;
-        const int walk_speed = 200;
+        const int walkSpeed = 200;
 
         Vector2 velocity;
 
@@ -232,11 +230,11 @@ This adds simple walking support by pressing left and right:
 
             if (Input.IsActionPressed("ui_left"))
             {
-                velocity.x = -walk_speed;
+                velocity.x = -walkSpeed;
             }
             else if (Input.IsActionPressed("ui_right"))
             {
-                velocity.x = walk_speed;
+                velocity.x = walkSpeed;
             }
             else
             {

+ 3 - 3
tutorials/physics/rigid_body.rst

@@ -48,7 +48,7 @@ Here is a custom ``look_at()`` method that will work reliably with rigid bodies:
 
     class Body : RigidBody
     {
-        private void lookFollow(PhysicsDirectBodyState state, Transform currentTransform, Vector3 targetPosition)
+        private void LookFollow(PhysicsDirectBodyState state, Transform currentTransform, Vector3 targetPosition)
         {
             var upDir = new Vector3(0, 1, 0);
             var curDir = currentTransform.basis.Xform(new Vector3(0, 0, 1));
@@ -60,8 +60,8 @@ Here is a custom ``look_at()`` method that will work reliably with rigid bodies:
 
         public override void _IntegrateForces(PhysicsDirectBodyState state)
         {
-            var targetPosition = (GetNode("my_target_spatial_node") as Spatial).GetGlobalTransform().origin;
-            lookFollow(state, GetGlobalTransform(), targetPosition);
+            var targetPosition = GetNode<Spatial>("my_target_spatial_node").GetGlobalTransform().origin;
+            LookFollow(state, GetGlobalTransform(), targetPosition);
         }
     }
 

+ 12 - 21
tutorials/physics/using_kinematic_body_2d.rst

@@ -194,31 +194,27 @@ Attach a script to the KinematicBody2D and add the following code:
         public int Speed = 250;
         private Vector2 _velocity = new Vector2();
 
-        public void getInput()
+        public void GetInput()
         {
             // Detect up/down/left/right keystate and only move when pressed
             _velocity = new Vector2();
+
             if (Input.IsActionPressed("ui_right"))
-            {
                 _velocity.x += 1;
-            }
+
             if (Input.IsActionPressed("ui_left"))
-            {
                 _velocity.x -= 1;
-            }
+
             if (Input.IsActionPressed("ui_down"))
-            {
                 _velocity.y += 1;
-            }
+
             if (Input.IsActionPressed("ui_up"))
-            {
                 _velocity.y -= 1;
-            }
         }
 
         public override void _PhysicsProcess(float delta)
         {
-            getInput();
+            GetInput();
             MoveAndCollide(velocity * delta);
         }
     }
@@ -302,7 +298,7 @@ uses the mouse pointer. Here is the code for the Player, using ``move_and_slide(
         public int Speed = 200;
         private Vector2 _velocity = new Vector2();
 
-        public void getInput()
+        public void GetInput()
         {
             // add these actions in Project Settings -> Input Map
             _velocity = new Vector2();
@@ -324,13 +320,13 @@ uses the mouse pointer. Here is the code for the Player, using ``move_and_slide(
         {
             // "Muzzle" is a Position2D placed at the barrel of the gun
             var b = (Bullet)_bullet.Instance();
-            b.Start(((Node2D)GetNode("Muzzle")).GlobalPosition, Rotation);
+            b.Start(GetNode<Node2D>("Muzzle").GlobalPosition, Rotation);
             GetParent().AddChild(b);
         }
 
         public override void _PhysicsProcess(float delta)
         {
-            getInput();
+            GetInput();
             var dir = GetGlobalMousePosition() - GlobalPosition;
             // Don't move if too close to the mouse pointer
             if (dir.Length() > 5)
@@ -478,7 +474,7 @@ Here's the code for the player body:
         Vector2 velocity = new Vector2();
         bool jumping = false;
 
-        public void getInput()
+        public void GetInput()
         {
             velocity.x = 0;
             bool right = Input.IsActionPressed("ui_right");
@@ -490,24 +486,19 @@ Here's the code for the player body:
                 jumping = true;
                 velocity.y = JumpSpeed;
             }
+
             if (right)
-            {
                 velocity.x += RunSpeed;
-            }
             if (left)
-            {
                 velocity.x -= RunSpeed;
-            }
         }
 
         public override void _PhysicsProcess(float delta)
         {
-            getInput();
+            GetInput();
             velocity.y += Gravity * delta;
             if (jumping && IsOnFloor())
-            {
                 jumping = false;
-            }
             velocity = MoveAndSlide(velocity, new Vector2(0, -1));
         }
     }