Godot Engine 4.0 Documentation - Step by Step Tutorial - Creating Your First Script

This article is the result of Google Translate's English translation, and DrGraph added some corrections on this basis. English original page:

Creating your first script — Godot Engine (stable) documentation in English

Create your first script¶

In this lesson, you'll write your first script to spin the Godot icon using GDScript. As we mentioned in the introduction , we assume you have a programming background. For convenience, the equivalent C# code has been included in another tab.

Reference: To learn more about GDScript, its keywords and syntax, go to GDScript Reference .

Reference: To learn more about C#, visit the C# Fundamentals page.

Project Settings¶

Please create a new project to start from scratch. Your project should include an image: the Godot icon, which we use a lot in the community for prototyping.

We need to create a Sprite2D node to display it in the game. In the scene dock, click the Other Nodes button.

Type "Sprite2D" in the search bar to filter the nodes, then double click on the Sprite2D to create the node.

Your scene tab should now only have a single Sprite2D node.

The Sprite2D node needs a texture [Texture] to display. In the Inspector on the right, you can see that the Texture property reads "[empty]". To display the Godot icon, click and drag the file icon.svgfrom the file system dock to the texture slot.

Note: You can automatically create Sprite2D nodes by dragging and dropping images on the viewport.

Then, click and drag the icon in the viewport to center it in the game view.

Create a new script¶

To create a new script and attach it to our node, right-click on the Sprite2D in the scene dock and select Attach Script.

The Attach Node Script window appears. It allows you to choose the script's language and file path, among other options.

Change the template field from "node: default" to "object: empty" to start with a clean file. Leave the other options as default and click the Create button to create the script.

The script workspace should appear with sprite_2d.gdthe new file you opened and the following line of code:

GD script
extends Sprite2D
C#

using Godot;

public partial class MySprite2D : Sprite2D
{
}

Every GDScript file is implicitly a class. keyword extendsdefines the classes this script inherits from or extends. In this case, it is Sprite2D, which means our script will have access to all properties and functions of the Sprite2D node, including classes it extends such as , Node2D, CanvasItemand  Node.

Note: In GDScript, if you omit the line with the keyword extends, your class will implicitly extend RefCounted , which Godot uses to manage the application's memory.

Inherited properties include those you can see in the Inspector dock, such as our node's texture.

Note: By default, the Inspector displays a node's properties in the "Title Case", with uppercase words separated by spaces. In GDScript code, these properties are in "snake_case", which is lowercase letters with underscores separating words.

You can hover over any property name in the inspector to see a description and its identifier in code.

Hello World!

Our script is currently not doing anything. Let's have it print the text "Hello, world!" to the bottom panel of the output to begin with.

Add the following code to your script:

GD script

func _init():
    print("Hello, world!")

C#
public MySprite2D()
{
    GD.Print("Hello, world!");
}

Let's break it down. keyword funcdefines a new function named  _init. This is a special name for our class's constructor. If you define this function, the engine will  _init()call it when each object or node is created in memory.

Note: GDScript is an indentation-based language. A tab at the beginning of the line indicates that print()it is required for the code to work. If you omit it or do not indent a line correctly, the editor will highlight it in red and display the following error message: "Expected indented block".

如果您还没有保存场景,可以将场景保存为sprite_2d.tscn, then press F6 (Cmd + R on macOS) to run it. View the expanded output bottom panel. It should display "Hello, world!".

After removing _init()the function, you are left with only one line of code.extends Sprite2D

Turn¶ _

Time to move and rotate our nodes. To do this, we will add two member variables to the script: the movement speed [speed] in pixels/second and the angular velocity [angular_speed] in radians/second. extends Sprite2DAdd the following content after [GDScript] .

GDScript
var speed = 400
var angular_speed = PI
C#
private int _speed = 400;
private float _angularSpeed = Mathf.Pi;

Member variables are located near the top of the script, after any "expand" lines, but before functions. Each node instance with this script attached will have its own copy of the speed and angular_speedproperties.

Note: Angles in Godot are measured in radians by default, but if you prefer to calculate angles in degrees, there are built-in functions and properties available.

To move our icon, we need to update its position and rotation [state] every frame in the game loop. We can use Nodethe virtual functions of the class _process(). If you define it in any Node-derived class, such as Sprite2D, Godot will call the function every frame and pass it a deltaparameter named , which is the elapsed time since the previous frame.

NOTE: Games work by rendering many images per second, each image is called a frame, and they do so in a loop. We measure the rate at which a game generates graphics in frames per second (FPS). Aim for 60 FPS for most games, although you may find 30 FPS on slower mobile devices, or 90 to 240 FPS in virtual reality games.

Engine and game developers do their best to update the game world and render graphics at constant intervals, but there are always small variations in frame rendering times. That's why the engine gives us this delta time value to make our motion independent of our frame rate.

At the bottom of the script, define the function:

GDScript
func _process(delta):
    rotation += angular_speed * delta
C#
public override void _Process(double delta)
{
    Rotation += _angularSpeed * (float)delta;
}

The keyword funcdefines a new function [GDScript]. After it, we have to write the name and parameters of the function in brackets. The colon ends the definition, and the following indented block is the content or instructions of the function.

Note: Notice how _process()[similar to] _init(), starts with a leading underscore. By convention, Godot's virtual functions, that is, built-in functions that you can override to communicate with the engine, begin with an underscore.

The code line in rotation += angular_speed * deltarotationNode2DSprite2D,the function is to increase the rotation of the sprite [Sprite] every frame. Here, [rotation] is an attribute inherited from the [Node2D] class, and [Sprite2D class] is extended. It controls the rotation of our node and uses radians.

Note: In the code editor, you can Ctrl-click any built-in property or function, such as position, rotation, or _processopen the corresponding document in a new tab.

Run the scene to see the Godot icon spin in place.

Note: In C#, be careful with _Process()the parameter delta为double类型. So when we apply it to the rotation, we need to convert it tofloat。

Move¶ _

Now let the nodes move. Add the following two lines inside the function _process() , making sure the new lines are indented the same as the lines before them.rotation += angular * delta

GDScript

var velocity = Vector2.UP.rotated(rotation) * speed

position += velocity * delta

C#

var velocity = Vector2.Up.Rotated(Rotation) * _speed;

Position += velocity * (float)delta;

As we have already seen, vara keyword defines a new variable. If you put it at the top of your script, it defines a property of the class. [Used here] Inside the function, it defines a local variable: it only exists within the scope of the function.

We define a velocitylocal variable called , which is a two-dimensional vector [Vector2] representing direction and velocity. To move the node forward, we Vector2.UPstart with a constant of the Vector2 class, an upward vector, and  rotated()rotate it by calling the method on it. This expression Vector2.UP.rotated(rotation)【为】is a vector pointing forward relative to our icon. Multiplied by our speed property, it gives us a velocity which we can use to move the node forward.

We add [ velocity * deltaposition】to the node's position property] to move it. The position [position] itself is a Vector2 type, which is a built-in type in Godot, representing a 2D vector.

Run the scene to see Godot turning in circles [running effect].

NOTE: Moving nodes like that will not take into account collisions with walls or floors. In your first 2D game , you'll learn another way to move objects while detecting collisions.

Our nodes currently move on their own. In the next section  , Listening to player input , we'll use player input to control it.

Full script¶

Here is the full sprite_2d.gdfile for reference.

GDScript

extends Sprite2D

var speed = 400
var angular_speed = PI


func _process(delta):
    rotation += angular_speed * delta

    var velocity = Vector2.UP.rotated(rotation) * speed

    position += velocity * delta

C#

using Godot;

public partial class MySprite2D : Sprite2D
{
    private int _speed = 400;
    private float _angularSpeed = Mathf.Pi;

    public override void _Process(double delta)
    {
        Rotation += _angularSpeed * (float)delta;
        var velocity = Vector2.Up.Rotated(Rotation) * _speed;

        Position += velocity * (float)delta;
    }
}

Guess you like

Origin blog.csdn.net/drgraph/article/details/130794797