Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

初めてのスクリプト作成

このレッスンでは、GDScript を使ってGodotアイコンを回転させるスクリプトをコーディングします。 in the introduction で触れたように、プログラミングの基礎知識があることを前提にしています。同等の C# コードは、便宜上、別のタブに含まれています。

../../_images/scripting_first_script_rotating_godot.gif

参考

GDScript、そのキーワード、およびその構文の詳細については、 GDScript reference にアクセスしてください。

参考

C#の詳細については、C# basics を参照してください。

プロジェクトの設定

Please create a new project to start with a clean slate. Your project should contain one picture: the Godot icon, which we often use for prototyping in the community.

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

../../_images/scripting_first_script_click_other_node.webp

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

../../_images/scripting_first_script_add_sprite_node.webp

Your Scene tab should now only have a Sprite2D node.

../../_images/scripting_first_script_scene_tree.webp

A Sprite2D node needs a texture to display. In the Inspector on the right, you can see that the Texture property says "[empty]". To display the Godot icon, click and drag the file icon.svg from the FileSystem dock onto the Texture slot.

../../_images/scripting_first_script_setting_texture.webp

注釈

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

次に、ビューポートの Godotアイコン をドラッグし、ゲームビューの中央に配置します。

../../_images/scripting_first_script_centering_sprite.webp

新規スクリプトの作成

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

../../_images/scripting_first_script_attach_script.webp

「ノードにスクリプトをアタッチする」("Attach node Script")ウィンドウが表示されます。このウィンドウでは、スクリプトの言語やファイルパスなどのオプションを選択できます。

Change the Template field from "Node: Default" to "Object: Empty" to start with a clean file. Leave the other options set to their default values and click the Create button to create the script.

../../_images/scripting_first_script_attach_node_script.webp

The Script workspace should appear with your new sprite_2d.gd file open and the following line of code:

extends Sprite2D

Every GDScript file is implicitly a class. The extends keyword defines the class this script inherits or extends. In this case, it's Sprite2D, meaning our script will get access to all the properties and functions of the Sprite2D node, including classes it extends, like Node2D, CanvasItem, and Node.

注釈

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

継承されたプロパティには、ノードの texture のように、インスペクタードックに表示されるプロパティも含まれます。

注釈

デフォルトでは、インスペクタータブ内ではノードのプロパティを「Title Case」(タイトルケース)で表示し、大文字の単語をスペースで区切ります。 GDScriptコード内では、これらのプロパティは「snake_case」(スネークケース)およびアンダースコアで区切られた小文字で表記します。

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

ハロー、ワールド!

現在、スクリプトは何もしません。 手始めに「Hello、world!」というテキストを下部[出力]パネルに表示させましょう。

スクリプトに次のコードを追加します。

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

こまかく見てみましょう。 func キーワードは、 _init という名前の新しい関数を定義します。これは、クラスのコンストラクターの特別な名前です。この関数を定義すると、エンジンがメモリ内にオブジェクトまたはノードを作成すると _init() が初期化のため呼ばれます。

注釈

GDScriptはインデントベースの言語です。コードが機能するには、 print() という行の先頭にあるタブが必要です。これを省略したり、行を正しくインデントしなかったりすると、エディターはそれを赤で強調表示し、"Unexpected indentation(予期しないインデント)" というエラーメッセージを表示します。

Save the scene as sprite_2d.tscn if you haven't already, then press F6 (Cmd + R on macOS) to run it. Look at the Output bottom panel that expands. It should display "Hello, world!".

../../_images/scripting_first_script_print_hello_world.webp

Delete the _init() function, so you're only left with the line extends Sprite2D.

回転させるには

It's time to make our node move and rotate. To do so, we're going to add two member variables to our script: the movement speed in pixels per second and the angular speed in radians per second. Add the following after the extends Sprite2D line.

var speed = 400
var angular_speed = PI

メンバー変数は、スクリプトの先頭付近、"extends" 行の後、関数の前に置かれます。このスクリプトがアタッチされているすべてのノードインスタンスは、 speed (速度)プロパティと angular_speed (角速度)プロパティの独自のコピーを持つことになります。

注釈

Godotの角度はデフォルトではラジアン単位で計算されますが、度単位で角度を計算したい場合に使える組み込み関数やプロパティも用意されています。

To move our icon, we need to update its position and rotation every frame in the game loop. We can use the _process() virtual function of the Node class. If you define it in any class that extends the Node class, like Sprite2D, Godot will call the function every frame and pass it an argument named delta, the time elapsed since the last frame.

注釈

ゲームは、1秒あたりに数多くの画像をレンダリングすることで機能します。各画像はフレームと呼ばれ、ループしてレンダリングされます。ゲームが画像を生成する速度をフレーム/秒(FPS)で測定します。ほとんどのゲームは60FPSを目指していますが、低速のモバイルデバイスでは30 FPS、バーチャルリアリティゲームでは90〜240のような数値が見られる場合があります。

エンジンとゲームの開発者は、一定の時間でゲームの世界を更新しレンダリングするために最善を尽くしますが、フレームのレンダリング時間には常に小さな変動があります。これはエンジンがフレームレートに依存しないモーションを作成するため提供するデルタタイムです。

スクリプトの最後に、関数を定義します。

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

func キーワードは新しい関数を定義します。その後、関数名と引数を括弧で囲んで記述する必要があります。コロンで定義を終了し、それに続くインデントされたブロックが関数のコンテンツまたは命令になります。

注釈

_init()_process() のように関数の先頭がアンダースコアで始まることに注意してください。慣例により、Godotの仮想関数、つまり、エンジンとやりとりするため オーバーライドされる組み込み関数は、アンダースコアから始まります。

The line inside the function, rotation += angular_speed * delta, increments our sprite's rotation every frame. Here, rotation is a property inherited from the class Node2D, which Sprite2D extends. It controls the rotation of our node and works with radians.

ちなみに

コードエディタで、「position」、「rotation」、「_ process」などの組み込みプロパティまたは関数をCtrlキーを押しながらクリックすると対応する説明文が新しいタブで開きます。

シーンを実行して、Godotアイコンが指定した位置で回転することを確認します。

../../_images/scripting_first_script_godot_turning_in_place.gif

注釈

In C#, notice how the delta argument taken by _Process() is a double. We therefore need to convert it to float when we apply it to the rotation.

前進させるには

Let's now make the node move. Add the following two lines inside of the _process() function, ensuring the new lines are indented the same way as the rotation += angular_speed * delta line before them.

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

position += velocity * delta

すでに見たように、 var キーワードは新しい変数を定義します。スクリプトの先頭に配置すると、クラスのプロパティとして定義されます。関数内で定義されたものはローカル変数となり、関数のスコープ内でのみ参照されます。

We define a local variable named velocity, a 2D vector representing both a direction and a speed. To make the node move forward, we start from the Vector2 class's constant Vector2.UP, a vector pointing up, and rotate it by calling the Vector2 method rotated(). 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 we can use to move the node forward.

ノードのpositionvelocity * deltaを追加して移動しています。このposition自体は Vector2 というタイプで、2次元ベクトルを表すGodotの組み込み型です。

シーンを実行してGodotの頭がぐるぐる回るのを確認してください。

../../_images/scripting_first_script_rotating_godot.gif

注釈

このようなノードの移動では、壁や床との衝突は考慮されません。 ref:doc_your_first_2d_game では、衝突を検出しながらオブジェクトを移動させる別のアプローチを学びます。

Our node currently moves by itself. In the next part, プレイヤーの入力を聞く, we'll use player input to control it.

完全なスクリプト

Here is the complete sprite_2d.gd file for reference.

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