4.0: Convert Sprite references to Sprite2D

Some screenshots will need to be updated so that the scene structures shown
in screenshot fit what the code blocks are referring to.
This commit is contained in:
Rémi Verschelde
2021-10-06 14:29:55 +02:00
parent 15f78ae0b9
commit 9a05eef561
37 changed files with 243 additions and 243 deletions
+1 -1
View File
@@ -83,7 +83,7 @@ Vulkan renderer.
- High-level tools to draw lines and polygons such as Polygon2D and Line2D.
- AnimatedSprite as a helper for creating animated sprites.
- AnimatedSprite2D as a helper for creating animated sprites.
- Parallax layers.
- Pseudo-3D support by automatically duplicating a layer several times.
@@ -125,19 +125,19 @@ the text. Here's the list of available tags:
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| Tag | Effect | Usage | Result |
+============================+======================================+===================================+===================================================+
| [Class] | Link a class | Move the [Sprite]. | Move the :ref:`class_sprite`. |
| [Class] | Link a class | Move the [Sprite2D]. | Move the :ref:`class_Sprite2D`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [method methodname] | Link to a method in this class | Call [method hide]. | See :ref:`hide <class_spatial_method_hide>`. |
| [method methodname] | Link to a method in this class | Call [method hide]. | Call :ref:`hide <class_Node3D_method_hide>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [method Class.methodname] | Link to another class's method | Call [method Spatial.hide]. | See :ref:`hide <class_spatial_method_hide>`. |
| [method Class.methodname] | Link to another class's method | Call [method Node3D.hide]. | Call :ref:`hide <class_Node3D_method_hide>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [member membername] | Link to a member in this class | Get [member scale]. | Get :ref:`scale <class_node2d_property_scale>`. |
| [member membername] | Link to a member in this class | Get [member scale]. | Get :ref:`scale <class_Node2D_property_scale>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [member Class.membername] | Link to another class's member | Get [member Node2D.scale]. | Get :ref:`scale <class_node2d_property_scale>`. |
| [member Class.membername] | Link to another class's member | Get [member Node2D.scale]. | Get :ref:`scale <class_Node2D_property_scale>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [signal signalname] | Link to a signal in this class | Emit [signal renamed]. | Emit :ref:`renamed <class_node_signal_renamed>`. |
| [signal signalname] | Link to a signal in this class | Emit [signal renamed]. | Emit :ref:`renamed <class_Node_signal_renamed>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [signal Class.signalname] | Link to another class's signal | Emit [signal Node.renamed]. | Emit :ref:`renamed <class_node_signal_renamed>`. |
| [signal Class.signalname] | Link to another class's signal | Emit [signal Node.renamed]. | Emit :ref:`renamed <class_Node_signal_renamed>`. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
| [b] [/b] | Bold | Some [b]bold[/b] text. | Some **bold** text. |
+----------------------------+--------------------------------------+-----------------------------------+---------------------------------------------------+
@@ -164,7 +164,7 @@ example:
[codeblock]
func _ready():
var sprite = get_node("Sprite")
var sprite = get_node("Sprite2D")
print(sprite.get_pos())
[/codeblock]
@@ -173,7 +173,7 @@ Will display as:
.. code-block:: gdscript
func _ready():
var sprite = get_node("Sprite")
var sprite = get_node("Sprite2D")
print(sprite.get_pos())
If you need to have different code version in GDScript and C#, use
@@ -189,13 +189,13 @@ workflow.
[codeblocks]
[gdscript]
func _ready():
var sprite = get_node("Sprite")
var sprite = get_node("Sprite2D")
print(sprite.get_pos())
[/gdscript]
[csharp]
public override void _Ready()
{
var sprite = GetNode("Sprite");
var sprite = GetNode("Sprite2D");
GD.Print(sprite.GetPos());
}
[/csharp]
@@ -207,14 +207,14 @@ The above will display as:
.. code-tab:: gdscript GDScript
func _ready():
var sprite = get_node("Sprite")
var sprite = get_node("Sprite2D")
print(sprite.get_pos())
.. code-tab:: csharp
public override void _Ready()
{
var sprite = GetNode("Sprite");
var sprite = GetNode("Sprite2D");
GD.Print(sprite.GetPos());
}
@@ -300,7 +300,7 @@ The exception is topics that explain static typing concepts to users.
const MainAttack := preload("res://fire_attack.gd")
var hit_points := 5
var name: String = "Bob"
var body_sprite := $Sprite as Sprite
var body_sprite := $Sprite2D as Sprite2D
**Do** write constants and variables with dynamic typing:
@@ -310,7 +310,7 @@ The exception is topics that explain static typing concepts to users.
const MainAttack = preload("res://fire_attack.gd")
var hit_points = 5
var name = "Bob"
var body_sprite = $Sprite
var body_sprite = $Sprite2D
**Don't** write functions with inferred arguments or return types:
+1 -1
View File
@@ -699,7 +699,7 @@ But this is not all, depending what you do, you will be greeted with
some (hopefully positive) surprises.
- If you inherit from :ref:`class_Node` (or any derived node type, such as
Sprite), your new class will appear in the editor, in the inheritance
Sprite2D), your new class will appear in the editor, in the inheritance
tree in the "Add Node" dialog.
- If you inherit from :ref:`class_Resource`, it will appear in the resource
list, and all the exposed properties can be serialized when
@@ -53,10 +53,10 @@ or :kbd:`Cmd + S` on macOS.
Sprite animation
~~~~~~~~~~~~~~~~
Click on the ``Player`` node and add an :ref:`AnimatedSprite
<class_AnimatedSprite>` node as a child. The ``AnimatedSprite`` will handle the
Click on the ``Player`` node and add an :ref:`AnimatedSprite2D
<class_AnimatedSprite2D>` node as a child. The ``AnimatedSprite2D`` will handle the
appearance and animations for our player. Notice that there is a warning symbol
next to the node. An ``AnimatedSprite`` requires a :ref:`SpriteFrames
next to the node. An ``AnimatedSprite2D`` requires a :ref:`SpriteFrames
<class_SpriteFrames>` resource, which is a list of the animations it can
display. To create one, find the ``Frames`` property in the Inspector and click
"[empty]" -> "New SpriteFrames". Click again to open the "SpriteFrames" panel:
@@ -74,7 +74,7 @@ side of the panel for the corresponding animation:
.. image:: img/spriteframes_panel2.png
The player images are a bit too large for the game window, so we need to scale
them down. Click on the ``AnimatedSprite`` node and set the ``Scale`` property
them down. Click on the ``AnimatedSprite2D`` node and set the ``Scale`` property
to ``(0.5, 0.5)``. You can find it in the Inspector under the ``Node2D``
heading.
@@ -55,7 +55,7 @@ Start by declaring the member variables this object will need:
#ifndef PLAYER_H
#define PLAYER_H
#include <AnimatedSprite.hpp>
#include <AnimatedSprite2D.hpp>
#include <Area2D.hpp>
#include <CollisionShape2D.hpp>
#include <Godot.hpp>
@@ -64,7 +64,7 @@ Start by declaring the member variables this object will need:
class Player : public godot::Area2D {
GODOT_CLASS(Player, godot::Area2D)
godot::AnimatedSprite *_animated_sprite;
godot::AnimatedSprite2D *_animated_sprite;
godot::CollisionShape2D *_collision_shape;
godot::Input *_input;
godot::Vector2 _screen_size; // Size of the game window.
@@ -120,7 +120,7 @@ a good time to find the size of the game window:
#include "player.hpp"
void Player::_ready() {
_animated_sprite = get_node<godot::AnimatedSprite>("AnimatedSprite");
_animated_sprite = get_node<godot::AnimatedSprite2D>("AnimatedSprite2D");
_collision_shape = get_node<godot::CollisionShape2D>("CollisionShape2D");
_input = godot::Input::get_singleton();
_screen_size = get_viewport_rect().size;
@@ -161,9 +161,9 @@ which returns ``true`` if it's pressed or ``false`` if it isn't.
if velocity.length() > 0:
velocity = velocity.normalized() * speed
$AnimatedSprite.play()
$AnimatedSprite2D.play()
else:
$AnimatedSprite.stop()
$AnimatedSprite2D.stop()
.. code-tab:: csharp
@@ -191,7 +191,7 @@ which returns ``true`` if it's pressed or ``false`` if it isn't.
velocity.y -= 1;
}
var animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite");
var animatedSprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
if (velocity.Length() > 0)
{
@@ -237,16 +237,16 @@ diagonal movement.
It's good to know but won't be necessary for the rest of this tutorial.
We also check whether the player is moving so we can call ``play()`` or
``stop()`` on the AnimatedSprite.
``stop()`` on the AnimatedSprite2D.
``$`` is shorthand for ``get_node()``. So in the code above,
``$AnimatedSprite.play()`` is the same as
``get_node("AnimatedSprite").play()``.
``$AnimatedSprite2D.play()`` is the same as
``get_node("AnimatedSprite2D").play()``.
.. tip:: In GDScript, ``$`` returns the node at the relative path from the
current node, or returns ``null`` if the node is not found. Since
AnimatedSprite is a child of the current node, we can use
``$AnimatedSprite``.
AnimatedSprite2D is a child of the current node, we can use
``$AnimatedSprite2D``.
Now that we have a movement direction, we can update the player's position. We
can also use ``clamp()`` to prevent it from leaving the screen. *Clamping* a
@@ -289,7 +289,7 @@ the player around the screen in all directions.
``Attempt to call function 'play' in base 'null instance' on a null
instance``
this likely means you spelled the name of the AnimatedSprite node
this likely means you spelled the name of the AnimatedSprite2D node
wrong. Node names are case-sensitive and ``$NodeName`` must match
the name you see in the scene tree.
@@ -297,7 +297,7 @@ Choosing animations
~~~~~~~~~~~~~~~~~~~
Now that the player can move, we need to change which animation the
AnimatedSprite is playing based on its direction. We have the "walk" animation,
AnimatedSprite2D is playing based on its direction. We have the "walk" animation,
which shows the player walking to the right. This animation should be flipped
horizontally using the ``flip_h`` property for left movement. We also have the
"up" animation, which should be flipped vertically with ``flip_v`` for downward
@@ -307,27 +307,27 @@ movement. Let's place this code at the end of the ``_process()`` function:
.. code-tab:: gdscript GDScript
if velocity.x != 0:
$AnimatedSprite.animation = "walk"
$AnimatedSprite.flip_v = false
$AnimatedSprite2D.animation = "walk"
$AnimatedSprite2D.flip_v = false
# See the note below about boolean assignment.
$AnimatedSprite.flip_h = velocity.x < 0
$AnimatedSprite2D.flip_h = velocity.x < 0
elif velocity.y != 0:
$AnimatedSprite.animation = "up"
$AnimatedSprite.flip_v = velocity.y > 0
$AnimatedSprite2D.animation = "up"
$AnimatedSprite2D.flip_v = velocity.y > 0
.. code-tab:: csharp
if (velocity.x != 0)
{
animatedSprite.Animation = "walk";
animatedSprite.FlipV = false;
animatedSprite2D.Animation = "walk";
animatedSprite2D.FlipV = false;
// See the note below about boolean assignment.
animatedSprite.FlipH = velocity.x < 0;
animatedSprite2D.FlipH = velocity.x < 0;
}
else if (velocity.y != 0)
{
animatedSprite.Animation = "up";
animatedSprite.FlipV = velocity.y > 0;
animatedSprite2D.Animation = "up";
animatedSprite2D.FlipV = velocity.y > 0;
}
.. code-tab:: cpp
@@ -351,19 +351,19 @@ movement. Let's place this code at the end of the ``_process()`` function:
.. code-tab :: gdscript GDScript
if velocity.x < 0:
$AnimatedSprite.flip_h = true
$AnimatedSprite2D.flip_h = true
else:
$AnimatedSprite.flip_h = false
$AnimatedSprite2D.flip_h = false
.. code-tab:: csharp
if (velocity.x < 0)
{
animatedSprite.FlipH = true;
animatedSprite2D.FlipH = true;
}
else
{
animatedSprite.FlipH = false;
animatedSprite2D.FlipH = false;
}
Play the scene again and check that the animations are correct in each of the
@@ -17,7 +17,7 @@ Click Scene -> New Scene and add the following nodes:
- :ref:`RigidBody2D <class_RigidBody2D>` (named ``Mob``)
- :ref:`AnimatedSprite <class_AnimatedSprite>`
- :ref:`AnimatedSprite2D <class_AnimatedSprite2D>`
- :ref:`CollisionShape2D <class_CollisionShape2D>`
- :ref:`VisibilityNotifier2D <class_VisibilityNotifier2D>`
@@ -31,7 +31,7 @@ box. This will ensure the mobs do not collide with each other.
.. image:: img/set_collision_mask.png
Set up the :ref:`AnimatedSprite <class_AnimatedSprite>` like you did for the
Set up the :ref:`AnimatedSprite2D <class_AnimatedSprite2D>` like you did for the
player. This time, we have 3 animations: ``fly``, ``swim``, and ``walk``. There
are two images for each animation in the art folder.
@@ -45,7 +45,7 @@ We'll select one of these animations randomly so that the mobs will have some
variety.
Like the player images, these mob images need to be scaled down. Set the
``AnimatedSprite``'s ``Scale`` property to ``(0.75, 0.75)``.
``AnimatedSprite2D``'s ``Scale`` property to ``(0.75, 0.75)``.
As in the ``Player`` scene, add a ``CapsuleShape2D`` for the collision. To align
the shape with the image, you'll need to set the ``Rotation Degrees`` property
@@ -80,14 +80,14 @@ Add a script to the ``Mob`` like this:
#ifndef MOB_H
#define MOB_H
#include <AnimatedSprite.hpp>
#include <AnimatedSprite2D.hpp>
#include <Godot.hpp>
#include <RigidBody2D.hpp>
class Mob : public godot::RigidBody2D {
GODOT_CLASS(Mob, godot::RigidBody2D)
godot::AnimatedSprite *_animated_sprite;
godot::AnimatedSprite2D *_animated_sprite;
public:
void _init() {}
@@ -106,18 +106,18 @@ and randomly choose one of the three animation types:
.. code-tab:: gdscript GDScript
func _ready():
$AnimatedSprite.playing = true
var mob_types = $AnimatedSprite.frames.get_animation_names()
$AnimatedSprite.animation = mob_types[randi() % mob_types.size()]
$AnimatedSprite2D.playing = true
var mob_types = $AnimatedSprite2D.frames.get_animation_names()
$AnimatedSprite2D.animation = mob_types[randi() % mob_types.size()]
.. code-tab:: csharp
public override void _Ready()
{
var animSprite = GetNode<AnimatedSprite>("AnimatedSprite");
animSprite.Playing = true;
string[] mobTypes = animSprite.Frames.GetAnimationNames();
animSprite.Animation = mobTypes[GD.Randi() % mobTypes.Length];
var animSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
animSprite2D.Playing = true;
string[] mobTypes = animSprite2D.Frames.GetAnimationNames();
animSprite2D.Animation = mobTypes[GD.Randi() % mobTypes.Length];
}
.. code-tab:: cpp
@@ -131,13 +131,13 @@ and randomly choose one of the three animation types:
void Mob::_ready() {
godot::Ref<godot::RandomNumberGenerator> random = godot::RandomNumberGenerator::_new();
random->randomize();
_animated_sprite = get_node<godot::AnimatedSprite>("AnimatedSprite");
_animated_sprite = get_node<godot::AnimatedSprite2D>("AnimatedSprite2D");
_animated_sprite->_set_playing(true);
godot::PoolStringArray mob_types = _animated_sprite->get_sprite_frames()->get_animation_names();
_animated_sprite->set_animation(mob_types[random->randi() % mob_types.size()]);
}
First, we get the list of animation names from the AnimatedSprite's ``frames``
First, we get the list of animation names from the AnimatedSprite2D's ``frames``
property. This returns an Array containing all three animation names: ``["walk",
"swim", "fly"]``.
@@ -57,7 +57,7 @@ exception, not the norm.
|image1|
Sprite is a Node2D, a CanvasItem and a Node. It has all the properties
Sprite2D is a Node2D, a CanvasItem and a Node. It has all the properties
and features of its three parent classes, like transforms or the ability
to draw custom shapes and render with a custom shader.
+1 -1
View File
@@ -15,7 +15,7 @@ pack information about your scene's content.
Here's the example of a ball. It's composed of a :ref:`RigidBody2D
<class_RigidBody2D>` node as its root named Ball, which allows the ball to fall
and bounce on walls, a :ref:`Sprite <class_Sprite>` node, and a
and bounce on walls, a :ref:`Sprite2D <class_Sprite2D>` node, and a
:ref:`CollisionShape2D <class_CollisionShape2D>`.
.. image:: img/instancing_ball_scene.png
@@ -36,21 +36,21 @@ icon, which we often use for prototyping in the community.
.. Godot icon
We need to create a Sprite node to display it in the game. In the Scene dock,
We need to create a Sprite2D node to display it in the game. In the Scene dock,
click the Other Node button.
.. image:: img/scripting_first_script_click_other_node.png
Type "Sprite" in the search bar to filter nodes and double-click on Sprite to
Type "Sprite2D" in the search bar to filter nodes and double-click on Sprite2D to
create the node.
.. image:: img/scripting_first_script_add_sprite_node.png
Your Scene tab should now only have a Sprite node.
Your Scene tab should now only have a Sprite2D node.
.. image:: img/scripting_first_script_scene_tree.png
A Sprite node needs a texture to display. In the Inspector on the right, you can
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.png`` from the FileSystem dock onto the Texture slot.
@@ -58,7 +58,7 @@ and drag the file ``icon.png`` from the FileSystem dock onto the Texture slot.
.. note::
You can create Sprite nodes automatically by dragging and dropping images on
You can create Sprite2D nodes automatically by dragging and dropping images on
the viewport.
.. image:: img/scripting_first_script_dragging_sprite.png
@@ -70,7 +70,7 @@ Then, click and drag the icon in the viewport to center it in the game view.
Creating a new script
---------------------
To create and attach a new script to our node, right-click on Sprite in the
To create and attach a new script to our node, right-click on Sprite2D in the
scene dock and select "Attach Script".
.. image:: img/scripting_first_script_attach_script.png
@@ -89,11 +89,11 @@ line of code:
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
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 ``Sprite``, meaning
our script will get access to all the properties and functions of the Sprite
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``.
@@ -143,7 +143,7 @@ the Output bottom panel that expands. It should display "Hello, world!"
.. image:: img/scripting_first_script_print_hello_world.png
Delete the ``_init()`` function, so you're only left with the line ``extends
Sprite``.
Sprite2D``.
Turning around
--------------
@@ -155,7 +155,7 @@ angular speed in radians per second.
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
extends Sprite2D
var speed = 400
var angular_speed = PI
@@ -170,7 +170,7 @@ and ``angular_speed`` properties.
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 Sprite, Godot
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.
@@ -207,7 +207,7 @@ instructions.
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 ``Sprite`` extends. It controls the rotation of
from the class ``Node2D``, which ``Sprite2D`` extends. It controls the rotation of
our node and works with radians.
.. tip:: In the code editor, you can ctrl-click on any built-in property or
@@ -89,12 +89,12 @@ constant of the built-in ``Vector`` type representing a 2D vector of length 0.
If the player presses the "ui_up" action, we then update the velocity's value,
causing the sprite to move forward.
Here is the complete ``Sprite.gd`` file for reference.
Here is the complete ``Sprite2D.gd`` file for reference.
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
extends Sprite2D
var speed = 400
var angular_speed = PI
+14 -14
View File
@@ -47,12 +47,12 @@ root.
.. image:: img/signals_02_2d_scene.png
In the FileSystem dock, click and drag the ``Sprite.tscn`` file you saved
In the FileSystem dock, click and drag the ``Sprite2D.tscn`` file you saved
previously onto the Node2D to instantiate it.
.. image:: img/signals_03_dragging_scene.png
We want to add another node as a sibling of the Sprite. To do so, right-click on
We want to add another node as a sibling of the Sprite2D. To do so, right-click on
Node2D and select Add Child Node.
.. image:: img/signals_04_add_child_node.png
@@ -84,9 +84,9 @@ Your scene tree and viewport should look like this.
Connecting a signal in the editor
---------------------------------
Here, we want to connect the Button's "pressed" signal to our Sprite, and we
Here, we want to connect the Button's "pressed" signal to our Sprite2D, and we
want to call a new function that will toggle its motion on and off. We need to
have a script attached to the Sprite node, which we do from the previous lesson.
have a script attached to the Sprite2D node, which we do from the previous lesson.
You can connect signals in the Node dock. Select the Button node and, on the
right side of the editor, click on the tab named "Node" next to the Inspector.
@@ -101,7 +101,7 @@ Double-click the "pressed" signal to open the node connection window.
.. image:: img/signals_12_node_connection.png
There, you can connect the signal to the Sprite node. The node needs a receiver
There, you can connect the signal to the Sprite2D node. The node needs a receiver
method, a function that Godot will call when the Button emits the signal. The
editor generates one for you. By convention, we name these callback methods
"_on_NodeName_signal_name". Here, it'll be "_on_Button_pressed".
@@ -133,7 +133,7 @@ connection. This feature is only available when connecting nodes in the editor.
Let's replace the line with the ``pass`` keyword with code that'll toggle the
node's motion.
Our Sprite moves thanks to code in the ``_process()`` function. Godot provides a
Our Sprite2D moves thanks to code in the ``_process()`` function. Godot provides a
method to toggle processing on and off: :ref:`Node.set_process()
<class_Node_method_set_process>`. Another method of the Node class,
``is_processing()``, returns ``true`` if idle processing is active. We can use
@@ -160,12 +160,12 @@ following code, which we saw two lessons ago:
var velocity = Vector2.UP.rotated(rotation) * speed
position += velocity * delta
Your complete Sprite.gd code should look like the following.
Your complete ``Sprite2D.gd`` code should look like the following.
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
extends Sprite2D
var speed = 400
var angular_speed = PI
@@ -192,7 +192,7 @@ that's useful to implement skill cooldown times, weapon reloading, and more.
Head back to the 2D workspace. You can either click the "2D" text at the top of
the window or press :kbd:`Ctrl + F2` (:kbd:`Alt + 2` on macOS).
In the Scene dock, right-click on the Sprite node and add a new node. Search for
In the Scene dock, right-click on the Sprite2D node and add a new node. Search for
Timer and add the corresponding node. Your scene should now look like this.
.. image:: img/signals_15_scene_tree.png
@@ -201,13 +201,13 @@ With the Timer node selected, go to the Inspector and check the **Autostart** pr
.. image:: img/signals_18_timer_autostart.png
Click the script icon next to Sprite to jump back to the scripting workspace.
Click the script icon next to Sprite2D to jump back to the scripting workspace.
.. image:: img/signals_16_click_script.png
We need to do two operations to connect the nodes via code:
1. Get a reference to the Timer from the Sprite.
1. Get a reference to the Timer from the Sprite2D.
2. Call the Timer's ``connect()`` method.
.. note:: To connect to a signal via code, you need to call the ``connect()``
@@ -221,20 +221,20 @@ in a variable.
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
extends Sprite2D
#...
func _ready():
var timer = get_node("Timer")
The function ``get_node()`` looks at the Sprite's children and gets nodes by
The function ``get_node()`` looks at the Sprite2D's children and gets nodes by
their name. For example, if you renamed the Timer node to "BlinkingTimer" in the
editor, you would have to change the call to ``get_node("BlinkingTimer")``.
.. add seealso to a page that explains node features.
We can now connect the Timer to the Sprite in the ``_ready()`` function.
We can now connect the Timer to the Sprite2D in the ``_ready()`` function.
.. tabs::
.. code-tab:: gdscript GDScript
+13 -13
View File
@@ -47,13 +47,13 @@ Nodes
The demo uses four different nodes:
* :ref:`CanvasModulate <class_CanvasModulate>`
* :ref:`Sprite <class_Sprite>`
* :ref:`Sprite2D <class_Sprite2D>`
* :ref:`Light2D <class_Light2D>`
* :ref:`LightOccluder2D <class_LightOccluder2D>`
:ref:`CanvasModulate<class_CanvasModulate>` is used to darken the scene.
:ref:`CanvasModulate <class_CanvasModulate>` is used to darken the scene.
:ref:`Sprites <class_Sprite>` are used to display the textures for the light blobs, the
:ref:`Sprite2Ds <class_Sprite2D>` are used to display the textures for the light blobs, the
background, and for the shadow casters.
:ref:`Light2Ds <class_Light2D>` are used to light the scene. The way a light typically works
@@ -85,8 +85,8 @@ halfway between the color of the light and the color underneath.
the color of the light.
For the demo the lights have two components, the :ref:`Light <class_Light2D>` itself (which
is the effect of the light), and a :ref:`Sprite <class_Sprite>` blob which is an image showing the
location of the light source. A child :ref:`Sprite <class_Sprite>` is not necessary to make a
is the effect of the light), and a :ref:`Sprite2D <class_Sprite2D>` blob which is an image showing the
location of the light source. A child :ref:`Sprite2D <class_Sprite2D>` is not necessary to make a
:ref:`Light <class_Light2D>` work.
.. image:: img/light_shadow_light_blob.png
@@ -99,9 +99,9 @@ Shadows are made by intersecting a :ref:`Light <class_Light2D>` with a :ref:`Lig
By default shadows are turned off. To turn them on click on the :ref:`Light <class_Light2D>`
and under the Shadows section check ``Enabled``.
In the demo we are using a :ref:`Sprite <class_Sprite>` with a Texture on it to make the "Shadow Casters",
In the demo we are using a :ref:`Sprite2D <class_Sprite2D>` with a Texture on it to make the "Shadow Casters",
but in reality all you need is a couple of :ref:`LightOccluder2Ds <class_LightOccluder2D>`. By itself
the :ref:`LightOccluder2D <class_LightOccluder2D>` looks like a dark spot and in this demo the :ref:`Sprite <class_Sprite>` is
the :ref:`LightOccluder2D <class_LightOccluder2D>` looks like a dark spot and in this demo the :ref:`Sprite2D <class_Sprite2D>` is
just a black square.
Step by step
@@ -110,7 +110,7 @@ Step by step
Now that we have covered the basics of the nodes being used, we can now walk step by step through
the process of making a scene like the one found in the demo.
First add a :ref:`Sprite <class_Sprite>` and set its texture to the `background image <https://raw.githubusercontent.com/godotengine/godot-demo-projects/master/2d/lights_and_shadows/background.png>`_. For your game this can be any
First add a :ref:`Sprite2D <class_Sprite2D>` and set its texture to the `background image <https://raw.githubusercontent.com/godotengine/godot-demo-projects/master/2d/lights_and_shadows/background.png>`_. For your game this can be any
background you choose. For this style of shadow it is most likely to be a floor texture.
.. image:: img/light_shadow_background.png
@@ -121,8 +121,8 @@ means that each light adds its own color to whatever is underneath.
.. image:: img/light_shadow_all_lights_no_blob.png
Next add a child :ref:`Sprite <class_Sprite>` to each of the :ref:`Light <class_Light2D>` nodes, and set
the :ref:`Sprite's <class_Sprite>` texture to the `blob image <https://raw.githubusercontent.com/godotengine/godot-demo-projects/master/2d/lights_and_shadows/spot.png>`_. Each of these
Next add a child :ref:`Sprite2D <class_Sprite2D>` to each of the :ref:`Light <class_Light2D>` nodes, and set
the :ref:`Sprite2D's <class_Sprite2D>` texture to the `blob image <https://raw.githubusercontent.com/godotengine/godot-demo-projects/master/2d/lights_and_shadows/spot.png>`_. Each of these
should stay centered on the :ref:`Light <class_Light2D>` node. The blob is the image of the light
itself while the :ref:`Light <class_Light2D>` shows the effect that the light has on the scene. The
:ref:`LightOccluder2D's <class_LightOccluder2D>` will treat the position of the light as the center of the :ref:`Light <class_Light2D>`
@@ -148,10 +148,10 @@ The demo uses a :ref:`Node <class_Node2D>` named "casters" to organize the shado
:ref:`Node2D <class_Node2D>` to the scene. It will be used to group all the shadow casters together.
This way we can show and hide them all at the same time.
Each shadow caster is made of a :ref:`Sprite <class_Sprite>`, with a :ref:`LightOccluder2D <class_LightOccluder2D>`
child. For the demo the :ref:`Sprite <class_Sprite>` has a texture
Each shadow caster is made of a :ref:`Sprite2D <class_Sprite2D>`, with a :ref:`LightOccluder2D <class_LightOccluder2D>`
child. For the demo the :ref:`Sprite2D <class_Sprite2D>` has a texture
set to the `caster image <https://raw.githubusercontent.com/godotengine/godot-demo-projects/master/2d/lights_and_shadows/caster.png>`_ and nothing else. The child :ref:`LightOccluder2D <class_LightOccluder2D>` is where all the magic happens. In a
game the :ref:`Sprite <class_Sprite>` could be more than a black box; it could be an image of whatever object is casting
game the :ref:`Sprite2D <class_Sprite2D>` could be more than a black box; it could be an image of whatever object is casting
the shadow: a wall, a magical chest, or anything else.
.. image:: img/light_shadow_sprites.png
+6 -6
View File
@@ -15,7 +15,7 @@ via ``Viewport`` and ``ViewportTexture``).
2D meshes are meshes that contain two-dimensional geometry (Z can be omitted or ignored) instead of 3D.
You can experiment creating them yourself using ``SurfaceTool`` from code and displaying them in a ``MeshInstance2D`` node.
Currently, the only way to generate a 2D mesh within the editor is by either importing an OBJ file as a mesh, or converting it from a Sprite.
Currently, the only way to generate a 2D mesh within the editor is by either importing an OBJ file as a mesh, or converting it from a Sprite2D.
Optimizing pixels drawn
-----------------------
@@ -27,15 +27,15 @@ or layering multiple images on top of each other with large transparent areas (f
Converting to a mesh will ensure that only the opaque parts will be drawn and the rest will be ignored.
Converting Sprites to 2D meshes
-------------------------------
Converting Sprite2Ds to 2D meshes
---------------------------------
You can take advantage of this optimization by converting a ``Sprite`` to a ``MeshInstance2D``.
You can take advantage of this optimization by converting a ``Sprite2D`` to a ``MeshInstance2D``.
Start with an image that contains large amounts of transparency on the edges, like this tree:
.. image:: img/mesh2d1.png
Put it in a ``Sprite`` and select "Convert to 2D Mesh" from the menu:
Put it in a ``Sprite2D`` and select "Convert to 2D Mesh" from the menu:
.. image:: img/mesh2d2.png
@@ -47,6 +47,6 @@ The default values are good enough for many cases, but you can change growth and
.. image:: img/mesh2d4.png
Finally, push the ``Convert 2D Mesh`` button and your Sprite will be replaced:
Finally, push the ``Convert 2D Mesh`` button and your Sprite2D will be replaced:
.. image:: img/mesh2d5.png
+2 -2
View File
@@ -19,8 +19,8 @@ Setup
-----
Each example below uses the same scene setup. Start with a ``KinematicBody2D`` with two
children: ``Sprite`` and ``CollisionShape2D``. You can use the Godot icon ("icon.png")
for the Sprite's texture or use any other 2D image you have.
children: ``Sprite2D`` and ``CollisionShape2D``. You can use the Godot icon ("icon.png")
for the Sprite2D's texture or use any other 2D image you have.
Open ``Project -> Project Settings`` and select the "Input Map" tab. Add the following
input actions (see :ref:`InputEvent <doc_inputevent>` for details):
+21 -21
View File
@@ -1,26 +1,26 @@
.. _doc_2d_sprite_animation:
2D Sprite animation
2D sprite animation
===================
Introduction
------------
In this tutorial, you'll learn how to create 2D animated
characters with the AnimatedSprite class and the AnimationPlayer. Typically, when you create or download an animated character, it
characters with the AnimatedSprite2D class and the AnimationPlayer. Typically, when you create or download an animated character, it
will come in one of two ways: as individual images or as a single sprite sheet
containing all the animation's frames. Both can be animated in Godot with the AnimatedSprite class.
containing all the animation's frames. Both can be animated in Godot with the AnimatedSprite2D class.
First, we'll use :ref:`AnimatedSprite <class_AnimatedSprite>` to
First, we'll use :ref:`AnimatedSprite2D <class_AnimatedSprite2D>` to
animate a collection of individual images. Then we will animate a sprite sheet using this class. Finally, we will learn another way to animate a sprite sheet
with :ref:`AnimationPlayer <class_AnimationPlayer>` and the *Animation*
property of :ref:`Sprite <class_Sprite>`.
property of :ref:`Sprite2D <class_Sprite2D>`.
.. note:: Art for the following examples by https://opengameart.org/users/ansimuz and by
https://opengameart.org/users/tgfcoder
Individual images with AnimatedSprite
-------------------------------------
Individual images with AnimatedSprite2D
---------------------------------------
In this scenario, you have a collection of images, each containing one of your
character's animation frames. For this example, we'll use the following
@@ -43,7 +43,7 @@ with the following nodes:
:ref:`Physics Introduction <doc_physics_introduction>` for more
information.
Now select the ``AnimatedSprite`` and in its *SpriteFrames* property, select
Now select the ``AnimatedSprite2D`` and in its *SpriteFrames* property, select
"New SpriteFrames".
.. image:: img/2d_animation_new_spriteframes.png
@@ -79,7 +79,7 @@ released.
extends KinematicBody2D
onready var _animated_sprite = $AnimatedSprite
onready var _animated_sprite = $AnimatedSprite2D
func _process(delta):
if Input.is_action_pressed("ui_right"):
@@ -91,7 +91,7 @@ released.
public class Character : KinematicBody2D
{
private AnimatedSprite _animatedSprite;
private AnimatedSprite2D _animatedSprite;
public override void _Ready()
{
@@ -112,16 +112,16 @@ released.
}
Sprite sheet with AnimatedSprite
--------------------------------
Sprite sheet with AnimatedSprite2D
----------------------------------
You can also easily animate from a sprite sheet with the class ``AnimatedSprite``. We will use this public domain sprite sheet:
You can also easily animate from a sprite sheet with the class ``AnimatedSprite2D``. We will use this public domain sprite sheet:
.. image:: img/2d_animation_frog_spritesheet.png
Right-click the image and choose "Save Image As" to download it, and then copy the image into your project folder.
Set up your scene tree the same way you did previously when using individual images. Select the ``AnimatedSprite`` and in its *SpriteFrames* property, select
Set up your scene tree the same way you did previously when using individual images. Select the ``AnimatedSprite2D`` and in its *SpriteFrames* property, select
"New SpriteFrames".
Click on the new SpriteFrames resource. This time, when the bottom panel appears, select "Add frames from a Sprite Sheet".
@@ -142,7 +142,7 @@ You will now see your animation under the list of animations in the bottom panel
.. image:: img/2d_animation_spritesheet_animation.png
Finally, check Playing on the AnimatedSprite in the inspector to see your frog jump!
Finally, check Playing on the AnimatedSprite2D in the inspector to see your frog jump!
.. image:: img/2d_animation_play_spritesheet_animation.png
@@ -151,7 +151,7 @@ Sprite sheet with AnimationPlayer
---------------------------------
Another way that you can animate when using a sprite sheet is to use a standard
:ref:`Sprite <class_Sprite>` node to display the texture, and then animating the
:ref:`Sprite2D <class_Sprite2D>` node to display the texture, and then animating the
change from texture to texture with :ref:`AnimationPlayer <class_AnimationPlayer>`.
Consider this sprite sheet, which contains 6 frames of animation:
@@ -182,7 +182,7 @@ your sprite sheet.
.. image:: img/2d_animation_setframes.png
Now try changing the value of the *Frame* property. You'll see that it ranges
from ``0`` to ``5`` and the image displayed by the Sprite changes accordingly.
from ``0`` to ``5`` and the image displayed by the Sprite2D changes accordingly.
This is the property we'll be animating.
Select the ``AnimationPlayer`` and click the "Animation" button followed by
@@ -191,7 +191,7 @@ click the "Loop" button so that our animation will repeat.
.. image:: img/2d_animation_new_animation.png
Now select the ``Sprite`` node and click the key icon to add a new track.
Now select the ``Sprite2D`` node and click the key icon to add a new track.
.. image:: img/2d_animation_new_track.png
@@ -208,7 +208,7 @@ Press "Play" on the animation to see how it looks.
Controlling an AnimationPlayer animation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Like with AnimatedSprite, you can control the animation via code using
Like with AnimatedSprite2D, you can control the animation via code using
the ``play()`` and ``stop()`` methods. Again, here is an example to play the
animation while the right arrow key is held, and stop it when the key is
released.
@@ -265,5 +265,5 @@ Summary
These examples illustrate the two classes you can use in Godot for
2D animation. ``AnimationPlayer`` is
a bit more complex than ``AnimatedSprite``, but it provides additional functionality, since you can also
animate other properties like position or scale. The class ``AnimationPlayer`` can also be used with an ``AnimatedSprite``. Experiment to see what works best for your needs.
a bit more complex than ``AnimatedSprite2D``, but it provides additional functionality, since you can also
animate other properties like position or scale. The class ``AnimationPlayer`` can also be used with an ``AnimatedSprite2D``. Experiment to see what works best for your needs.
+1 -1
View File
@@ -9,7 +9,7 @@ Introduction
A tilemap is a grid of tiles used to create a game's layout. There are several
benefits to using :ref:`TileMap <class_TileMap>` nodes to design your levels.
First, they make it possible to draw the layout by "painting" the tiles onto a
grid, which is much faster than placing individual :ref:`Sprite <class_Sprite>`
grid, which is much faster than placing individual :ref:`Sprite2D <class_Sprite2D>`
nodes one by one. Second, they allow for much larger levels because they are
optimized for drawing large numbers of tiles. Finally, you can add collision,
occlusion, and navigation shapes to tiles, adding additional functionality to
+4 -4
View File
@@ -32,7 +32,7 @@ Godot provides tools for working with cutout rigs, and is ideal for the workflow
means animations can control much more than just motion of objects. Textures,
sprite sizes, pivots, opacity, color modulation, and more, can all be animated
and blended.
- **Combine animation styles**: AnimatedSprite allows traditional cel animation
- **Combine animation styles**: AnimatedSprite2D allows traditional cel animation
to be used alongside cutout animation. In cel animation different animation
frames use entirely different drawings rather than the same pieces positioned
differently. In an otherwise cutout-based animation, cel animation can be used
@@ -87,7 +87,7 @@ and dragging with the left mouse button. To exit rotate mode hit :kbd:`ESC`.
The rotation pivot is wrong and needs to be adjusted.
This small cross in the middle of the :ref:`Sprite <class_Sprite>` is
This small cross in the middle of the :ref:`Sprite2D <class_Sprite2D>` is
the rotation pivot:
.. image:: img/tuto_cutout4.png
@@ -96,13 +96,13 @@ Adjusting the pivot
~~~~~~~~~~~~~~~~~~~
The pivot can be adjusted by changing the *offset* property in the
Sprite:
Sprite2D:
.. image:: img/tuto_cutout5.png
The pivot can also be adjusted *visually*. While hovering over the
desired pivot point, press :kbd:`V` to move the pivot there for the
selected Sprite. There is also a tool in the tool bar that has a
selected Sprite2D. There is also a tool in the tool bar that has a
similar function.
.. image:: img/tutovec_torso2.gif
+2 -2
View File
@@ -86,7 +86,7 @@ at various points, and change their timing.
Each line in the Animation Panel is an animation track that references a
Normal or Transform property of a node. Each track stores a path to
a node and its affected property. For example, the position track
in the illustration refers to to the ``position`` property of the Sprite
in the illustration refers to to the ``position`` property of the Sprite2D
node.
.. figure:: img/animation_normal_track.png
@@ -124,7 +124,7 @@ its child. We will animate the sprite to move between two points on the screen.
Therefore, it is not recommended to add nodes that have a 2D/3D transform
as a child of an AnimationPlayer node.
The sprite holds an image texture. For this tutorial, select the Sprite node,
The sprite holds an image texture. For this tutorial, select the Sprite2D node,
click Texture in the Inspector, and then click Load. Select the default Godot
icon for the sprite's texture.
@@ -303,8 +303,8 @@ to group them together as related concepts, then it makes sense to use them as
strings. That way, a separate data structure to execute on the printing is
unnecessary.
AnimatedTexture vs. AnimatedSprite vs. AnimationPlayer vs. AnimationTree
------------------------------------------------------------------------
AnimatedTexture vs. AnimatedSprite2D vs. AnimationPlayer vs. AnimationTree
--------------------------------------------------------------------------
Under what circumstances should one use each of Godot's animation classes?
The answer may not be immediately clear to new Godot users.
@@ -324,13 +324,13 @@ that users have very little control.
Also note that AnimatedTexture is a :ref:`Resource <class_Resource>` unlike
the other :ref:`Node <class_Node>` objects discussed here. One might create
a :ref:`Sprite <class_Sprite>` node that uses AnimatedTexture as its texture.
a :ref:`Sprite2D <class_Sprite2D>` node that uses AnimatedTexture as its texture.
Or (something the others can't do) one could add AnimatedTextures as tiles
in a :ref:`TileSet <class_TileSet>` and integrate it with a
:ref:`TileMap <class_TileMap>` for many auto-animating backgrounds that
all render in a single batched draw call.
The AnimatedSprite node, in combination with the
The AnimatedSprite2D node, in combination with the
:ref:`SpriteFrames <class_SpriteFrames>` resource, allows one to create a
variety of animation sequences through spritesheets, flip between animations,
and control their speed, regional offset, and orientation. This makes them
@@ -340,7 +340,7 @@ If one needs trigger other effects in relation to animation changes (for
example, create particle effects, call functions, or manipulate other
peripheral elements besides the frame-based animation), then will need to use
an :ref:`AnimationPlayer <class_AnimationPlayer>` node in conjunction with
the AnimatedSprite.
the AnimatedSprite2D.
AnimationPlayers are also the tool one will need to use if they wish to design
more complex 2D animation systems, such as...
+1 -1
View File
@@ -14,7 +14,7 @@ The second way is more customizable, but involves scripting:
.. note::
You could display a "software" mouse cursor by hiding the mouse cursor and
moving a Sprite to the cursor position in a ``_process`` method, but this
moving a Sprite2D to the cursor position in a ``_process`` method, but this
will add at least one frame of latency compared to an "hardware" mouse
cursor. Therefore, it's recommended to use the approach described here
whenever possible.
+4 -4
View File
@@ -303,7 +303,7 @@ Mouse motion
the mouse moves. You can find the move's distance with the ``relative``
property.
Here's an example using mouse events to drag-and-drop a :ref:`Sprite <class_Sprite>`
Here's an example using mouse events to drag-and-drop a :ref:`Sprite2D <class_Sprite2D>`
node:
.. tabs::
@@ -318,7 +318,7 @@ node:
func _input(event):
if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
if (event.position - $Sprite.position).length() < click_radius:
if (event.position - $Sprite2D.position).length() < click_radius:
# Start dragging if the click is on the sprite.
if not dragging and event.pressed:
dragging = true
@@ -328,7 +328,7 @@ node:
if event is InputEventMouseMotion and dragging:
# While dragging, move the sprite with the mouse.
$Sprite.position = event.position
$Sprite2D.position = event.position
.. code-tab:: csharp
@@ -342,7 +342,7 @@ node:
public override void _Input(InputEvent inputEvent)
{
Sprite sprite = GetNodeOrNull<Sprite>("Sprite");
Sprite2D sprite = GetNodeOrNull<Sprite2D>("Sprite2D");
if (sprite == null)
{
return; // No suitable node was found.
+2 -2
View File
@@ -43,7 +43,7 @@ Here is example pseudo-code for going from point A to B using interpolation:
func _physics_process(delta):
t += delta * 0.4
$Sprite.position = $A.position.linear_interpolate($B.position, t)
$Sprite2D.position = $A.position.linear_interpolate($B.position, t)
It will produce the following motion:
@@ -89,7 +89,7 @@ Interpolation can be used to smooth movement, rotation, etc. Here is an example
func _physics_process(delta):
var mouse_pos = get_local_mouse_position()
$Sprite.position = $Sprite.position.linear_interpolate(mouse_pos, delta * FOLLOW_SPEED)
$Sprite2D.position = $Sprite2D.position.linear_interpolate(mouse_pos, delta * FOLLOW_SPEED)
Here is how it looks:
+1 -1
View File
@@ -235,7 +235,7 @@ Putting it all together
~~~~~~~~~~~~~~~~~~~~~~~
We're going to apply everything we mentioned so far onto one transform.
To follow along, create a project with a Sprite node and use the
To follow along, create a project with a Sprite2D node and use the
Godot logo for the texture resource.
Let's set the translation to (350, 150), rotate by -0.5 rad, and scale by 3.
+3 -3
View File
@@ -87,8 +87,8 @@ If it is set to **Solids** (the default), collisions will include the polygon
and its contained area. If it is set to **Segments**, collisions will only
include the polygon edges.
You can generate a concave collision shape from the editor by selecting a Sprite
and using the **Sprite** menu at the top of the 2D viewport. The Sprite menu
You can generate a concave collision shape from the editor by selecting a Sprite2D
and using the **Sprite2D** menu at the top of the 2D viewport. The Sprite2D menu
dropdown exposes an option called **Create CollisionPolygon2D Sibling**.
Once you click it, it displays a menu with 3 settings:
@@ -108,7 +108,7 @@ Once you click it, it displays a menu with 3 settings:
be blocked by small, decorative details.
To use a separate image for collision polygon generation, create another
Sprite, generate a collision polygon sibling from it then remove the Sprite
Sprite2D, generate a collision polygon sibling from it then remove the Sprite2D
node. This way, you can exclude small details from the generated collision.
Performance caveats
@@ -199,9 +199,9 @@ Movement and walls
If you've downloaded the sample project, this example is in "BasicMovement.tscn".
For this example, add a ``KinematicBody2D`` with two children: a ``Sprite`` and a
``CollisionShape2D``. Use the Godot "icon.png" as the Sprite's texture (drag it
from the Filesystem dock to the *Texture* property of the ``Sprite``). In the
For this example, add a ``KinematicBody2D`` with two children: a ``Sprite2D`` and a
``CollisionShape2D``. Use the Godot "icon.png" as the Sprite2D's texture (drag it
from the Filesystem dock to the *Texture* property of the ``Sprite2D``). In the
``CollisionShape2D``'s *Shape* property, select "New RectangleShape2D" and
size the rectangle to fit over the sprite image.
@@ -15,7 +15,7 @@ This short tutorial will explain how to make a Perlin-3D noise node (original
code from this `GPU noise shaders plugin
<https://github.com/curly-brace/Godot-3.0-Noise-Shaders/blob/master/assets/gpu_noise_shaders/classic_perlin3d.tres>`_.
Create a Sprite and assign a :ref:`class_ShaderMaterial` to its material slot:
Create a Sprite2D and assign a :ref:`class_ShaderMaterial` to its material slot:
.. image:: img/visual_shader_plugins_start.png
@@ -23,7 +23,7 @@ Assign :ref:`class_VisualShader` to the shader slot of the material:
.. image:: img/visual_shader_plugins_start2.png
Don't forget to change its mode to "CanvasItem" (if you are using a Sprite):
Don't forget to change its mode to "CanvasItem" (if you are using a Sprite2D):
.. image:: img/visual_shader_plugins_start3.png
@@ -114,14 +114,14 @@ Here is how a ``_process()`` function might look for you:
Try it out
-----------
Add a ``Sprite`` node to your scene and set the texture to Godot icon. Attach
Add a ``Sprite2D`` node to your scene and set the texture to Godot icon. Attach
and open a script, and change it to this:
.. tabs::
.. code-tab:: gdscript GDScript
tool
extends Sprite
extends Sprite2D
func _process(delta):
rotation_degrees += 180 * delta
@@ -132,7 +132,7 @@ and open a script, and change it to this:
using System;
[Tool]
public class MySprite : Sprite
public class MySprite : Sprite2D
{
public override void _Process(float delta)
{
@@ -189,7 +189,7 @@ Add and export a variable speed to the script. The function set_speed after
.. code-tab:: gdscript GDScript
tool
extends Sprite
extends Sprite2D
export var speed = 1 setget set_speed
@@ -210,7 +210,7 @@ Add and export a variable speed to the script. The function set_speed after
using System;
[Tool]
public class MySprite : Sprite
public class MySprite : Sprite2D
{
private float speed = 1;
+1 -1
View File
@@ -146,7 +146,7 @@ following code:
# Convert Image to ImageTexture.
var tex = ImageTexture.new()
tex.create_from_image(img)
# Set Sprite Texture.
# Set sprite texture.
$sprite.texture = tex
But if you use this in ``_ready()`` or from the first frame of the :ref:`Viewport's <class_Viewport>` initialization,
@@ -19,28 +19,28 @@ C# is a statically typed language. Therefore, you can't do the following:
mySprite.SetFrame(0);
The method ``GetNode()`` returns a ``Node`` instance.
You must explicitly convert it to the desired derived type, ``Sprite`` in this case.
You must explicitly convert it to the desired derived type, ``Sprite2D`` in this case.
For this, you have various options in C#.
**Casting and Type Checking**
Throws ``InvalidCastException`` if the returned node cannot be cast to Sprite.
Throws ``InvalidCastException`` if the returned node cannot be cast to Sprite2D.
You would use it instead of the ``as`` operator if you are pretty sure it won't fail.
.. code-block:: csharp
Sprite mySprite = (Sprite)GetNode("MySprite");
Sprite2D mySprite = (Sprite2D)GetNode("MySprite");
mySprite.SetFrame(0);
**Using the AS operator**
The ``as`` operator returns ``null`` if the node cannot be cast to Sprite,
The ``as`` operator returns ``null`` if the node cannot be cast to Sprite2D,
and for that reason, it cannot be used with value types.
.. code-block:: csharp
Sprite mySprite = GetNode("MySprite") as Sprite;
Sprite2D mySprite = GetNode("MySprite") as Sprite2D;
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);
@@ -52,28 +52,28 @@ Generic methods are also provided to make this type conversion transparent.
.. code-block:: csharp
Sprite mySprite = GetNode<Sprite>("MySprite");
Sprite2D mySprite = GetNode<Sprite2D>("MySprite");
mySprite.SetFrame(0);
``GetNodeOrNull<T>()`` uses the ``as`` operator and will return ``null`` if the node cannot be cast to the desired type.
.. code-block:: csharp
Sprite mySprite = GetNodeOrNull<Sprite>("MySprite");
Sprite2D mySprite = GetNodeOrNull<Sprite2D>("MySprite");
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);
**Type checking using the IS operator**
To check if the node can be cast to Sprite, you can use the ``is`` operator.
The ``is`` operator returns false if the node cannot be cast to Sprite,
To check if the node can be cast to Sprite2D, you can use the ``is`` operator.
The ``is`` operator returns false if the node cannot be cast to Sprite2D,
otherwise it returns true.
.. code-block:: csharp
if (GetNode("MySprite") is Sprite)
if (GetNode("MySprite") is Sprite2D)
{
// Yup, it's a sprite!
// Yup, it's a Sprite2D!
}
For more advanced type checking, you can look into `Pattern Matching <https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching>`_.
@@ -178,12 +178,12 @@ GDNative node we'll be creating. We will name it ``gdexample.h``:
#define GDEXAMPLE_H
#include <Godot.hpp>
#include <Sprite.hpp>
#include <Sprite2D.hpp>
namespace godot {
class GDExample : public Sprite {
GODOT_CLASS(GDExample, Sprite)
class GDExample : public Sprite2D {
GODOT_CLASS(GDExample, Sprite2D)
private:
float time_passed;
@@ -209,11 +209,11 @@ GDNative node we'll be creating. We will name it ``gdexample.h``:
#define GDEXAMPLE_H
#include <Godot.hpp>
#include <Sprite.hpp>
#include <Sprite2D.hpp>
namespace godot {
class GDExample : public godot::GodotScript<Sprite> {
class GDExample : public godot::GodotScript<Sprite2D> {
GODOT_CLASS(GDExample)
private:
@@ -233,14 +233,14 @@ GDNative node we'll be creating. We will name it ``gdexample.h``:
#endif
There are a few things of note to the above. We're including ``Godot.hpp`` which
contains all our basic definitions. After that, we include ``Sprite.hpp`` which
contains bindings to the Sprite class. We'll be extending this class in our
contains all our basic definitions. After that, we include ``Sprite2D.hpp`` which
contains bindings to the Sprite2D class. We'll be extending this class in our
module.
We're using the namespace ``godot``, since everything in GDNative is defined
within this namespace.
Then we have our class definition, which inherits from our Sprite through a
Then we have our class definition, which inherits from our Sprite2D through a
container class. We'll see a few side effects of this later on. The
``GODOT_CLASS`` macro sets up a few internal things for us.
@@ -331,8 +331,8 @@ it. However, we do not have to tell Godot about our constructor, destructor and
The other method of note is our ``_process`` function, which keeps track
of how much time has passed and calculates a new position for our sprite using a
sine and cosine function. What stands out is calling
``owner->set_position`` to call one of the build in methods of our Sprite. This
is because our class is a container class; ``owner`` points to the actual Sprite
``owner->set_position`` to call one of the build in methods of our Sprite2D. This
is because our class is a container class; ``owner`` points to the actual Sprite2D
node our script relates to. In the upcoming NativeScript 1.1, ``set_position``
can be called directly on our class.
@@ -480,7 +480,7 @@ library contains our NativeScript. It also defines the ``class_name`` which
identifies the NativeScript in our plugin we want to use.
Time to jump back into Godot. We load up the main scene we created way back in
the beginning and now add a Sprite to our scene:
the beginning and now add a Sprite2D to our scene:
.. image:: img/gdnative_cpp_nodes.png
@@ -831,7 +831,7 @@ script on our main node and implemented our signal like this:
extends Node
func _on_Sprite_position_changed(node, new_pos):
func _on_Sprite2D_position_changed(node, new_pos):
print("The position of " + node.name + " is now " + str(new_pos))
Every second we simply output our position to the console.
@@ -171,15 +171,15 @@ be used in the documentation. Here's the list of available tags:
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| Tag | Effect | Usage | Result |
+===========================+================================+===================================+===================================================+
| [Class] | Link a class | Move the [Sprite]. | Move the :ref:`class_sprite`. |
| [Class] | Link a class | Move the [Sprite2D]. | Move the :ref:`class_Sprite2D`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| [method methodname] | Link to a method in this class | Call [method hide]. | See :ref:`hide <class_spatial_method_hide>`. |
| [method methodname] | Link to a method in this class | Call [method hide]. | Call :ref:`hide <class_Node3D_method_hide>`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| [method Class.methodname] | Link to another class's method | Call [method Spatial.hide]. | See :ref:`hide <class_spatial_method_hide>`. |
| [method Class.methodname] | Link to another class's method | Call [method Node3D.hide]. | Call :ref:`hide <class_Node3D_method_hide>`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| [member membername] | Link to a member in this class | Get [member scale]. | Get :ref:`scale <class_node2d_property_scale>`. |
| [member membername] | Link to a member in this class | Get [member scale]. | Get :ref:`scale <class_Node2D_property_scale>`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| [member Class.membername] | Link to another class's member | Get [member Node2D.scale]. | Get :ref:`scale <class_node2d_property_scale>`. |
| [member Class.membername] | Link to another class's member | Get [member Node2D.scale]. | Get :ref:`scale <class_Node2D_property_scale>`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
| [signal signalname] | Link to a signal in this class | Emit [signal renamed]. | Emit :ref:`renamed <class_node_signal_renamed>`. |
+---------------------------+--------------------------------+-----------------------------------+---------------------------------------------------+
@@ -88,7 +88,7 @@ Here is the code for the player using signals to emit the bullet:
.. tabs::
.. code-tab:: gdscript GDScript
extends Sprite
extends Sprite2D
signal shoot(bullet, direction, location)
@@ -104,7 +104,7 @@ Here is the code for the player using signals to emit the bullet:
.. code-tab:: csharp
public class Player : Sprite
public class Player : Sprite2D
{
[Signal]
delegate void Shoot(PackedScene bullet, Vector2 direction, Vector2 location);
@@ -15,7 +15,7 @@ present in the scene tree. Getting it in the parent node's ``_ready()`` function
guarantees that.
If, for example, you have a scene tree like this, and you want to get a reference to the
Sprite and Camera2D nodes to access them in your script.
Sprite2D and Camera2D nodes to access them in your script.
.. image:: img/nodes_and_scene_instances_player_scene_example.png
@@ -24,32 +24,32 @@ To do so, you can use the following code.
.. tabs::
.. code-tab:: gdscript GDScript
var sprite
var sprite2d
var camera2d
func _ready():
sprite = get_node("Sprite")
sprite2d = get_node("Sprite2D")
camera2d = get_node("Camera2D")
.. code-tab:: csharp
private Sprite _sprite;
private Camera2D _camera2d;
private Sprite2D _sprite2D;
private Camera2D _camera2D;
public override void _Ready()
{
base._Ready();
_sprite = GetNode<Sprite>("Sprite");
_camera2d = GetNode<Camera2D>("Camera2D");
_sprite2D = GetNode<Sprite2D>("Sprite2D");
_camera2D = GetNode<Camera2D>("Camera2D");
}
Note that you get nodes using their name, not their type. Above, "Sprite" and
Note that you get nodes using their name, not their type. Above, "Sprite2D" and
"Camera2D" are the nodes' names in the scene.
.. image:: img/nodes_and_scene_instances_sprite_node.png
If you rename the Sprite node as Skin in the Scene dock, you have to change the
If you rename the Sprite2D node as Skin in the Scene dock, you have to change the
line that gets the node to ``get_node("Skin")`` in the script.
.. image:: img/nodes_and_scene_instances_sprite_node_renamed.png
@@ -102,14 +102,14 @@ the ``_ready()`` callback.
.. code-block:: gdscript
onready var sprite = get_node("Sprite")
onready var sprite2d = get_node("Sprite2D")
There is also a short notation for ``get_node()``: the dollar sign, "$". You
place it before the name or path of the node you want to get.
.. code-block:: gdscript
onready var sprite = $Sprite
onready var sprite2d = $Sprite2D
onready var tween = $ShieldBar/Tween
Creating nodes
@@ -125,22 +125,22 @@ script.
.. tabs::
.. code-tab:: gdscript GDScript
var sprite
var sprite2d
func _ready():
var sprite = Sprite.new() # Create a new Sprite.
add_child(sprite) # Add it as a child of this node.
var sprite2d = Sprite2D.new() # Create a new Sprite2D.
add_child(sprite2d) # Add it as a child of this node.
.. code-tab:: csharp
private Sprite _sprite;
private Sprite2D _sprite2D;
public override void _Ready()
{
base._Ready();
_sprite = new Sprite(); // Create a new Sprite.
AddChild(_sprite); // Add it as a child of this node.
_sprite2D = new Sprite2D(); // Create a new Sprite2D.
AddChild(_sprite2D); // Add it as a child of this node.
}
To delete a node and free it from memory, you can call its ``queue_free()``
@@ -151,13 +151,13 @@ the scene and frees the object in memory.
.. tabs::
.. code-tab:: gdscript GDScript
sprite.queue_free()
sprite2d.queue_free()
.. code-tab:: csharp
_sprite.QueueFree();
_sprite2D.QueueFree();
Before calling ``sprite.queue_free()``, the remote scene tree looks like this.
Before calling ``sprite2d.queue_free()``, the remote scene tree looks like this.
.. image:: img/nodes_and_scene_instances_remote_tree_with_sprite.png
+2 -2
View File
@@ -44,7 +44,7 @@ There are two ways to save resources. They can be:
2. **Built-in**, saved inside the ``.tscn`` or the ``.scn`` file they're attached to.
To be more specific, here's a :ref:`Texture <class_Texture>`
in a :ref:`Sprite <class_Sprite>` node:
in a :ref:`Sprite2D <class_Sprite2D>` node:
.. image:: img/spriteprop.png
@@ -83,7 +83,7 @@ There are two ways to load resources from code. First, you can use the ``load()`
public override void _Ready()
{
var texture = (Texture)GD.Load("res://robi.png"); // Godot loads the Resource when it reads the line.
var sprite = GetNode<Sprite>("sprite");
var sprite = GetNode<Sprite2D>("sprite");
sprite.Texture = texture;
}
@@ -132,7 +132,7 @@ is usually:
| in bool **AT_LIGHT_PASS** | ``true`` if this is a light pass. |
+--------------------------------+---------------------------------------------------+
| in vec2 **TEXTURE_PIXEL_SIZE** | Normalized pixel size of default 2D texture. |
| | For a Sprite with a texture of size 64x32px, |
| | For a Sprite2D with a texture of size 64x32px, |
| | **TEXTURE_PIXEL_SIZE** = :code:`vec2(1/64, 1/32)` |
+--------------------------------+---------------------------------------------------+
| inout vec2 **VERTEX** | Vertex, in image space. |
@@ -147,7 +147,7 @@ is usually:
Fragment built-ins
^^^^^^^^^^^^^^^^^^
Certain Nodes (for example, :ref:`Sprites <class_Sprite>`) display a texture by default. However,
Certain Nodes (for example, :ref:`Sprite2Ds <class_Sprite2D>`) display a texture by default. However,
when a custom fragment function is attached to these nodes, the texture lookup needs to be done
manually. Godot does not provide the texture color in the ``COLOR`` built-in variable; to read
the texture color for such nodes, use:
@@ -185,7 +185,7 @@ it to the ``NORMALMAP`` property. Godot will handle converting it for use in 2D
| sampler2D **TEXTURE** | Default 2D texture. |
+---------------------------------------------+---------------------------------------------------------------+
| in vec2 **TEXTURE_PIXEL_SIZE** | Normalized pixel size of default 2D texture. |
| | For a Sprite with a texture of size 64x32px, |
| | For a Sprite2D with a texture of size 64x32px, |
| | **TEXTURE_PIXEL_SIZE** = :code`vec2(1/64, 1/32)` |
+---------------------------------------------+---------------------------------------------------------------+
| sampler2D **SPECULAR_SHININESS_TEXTURE** | |
@@ -244,7 +244,7 @@ When the shader is on a light pass, the ``AT_LIGHT_PASS`` variable will be ``tru
| sampler2D **TEXTURE** | Current texture in use for CanvasItem. |
+--------------------------------+------------------------------------------------------------------------------+
| in vec2 **TEXTURE_PIXEL_SIZE** | Normalized pixel size of default 2D texture. |
| | For a Sprite with a texture of size 64x32px, |
| | For a Sprite2D with a texture of size 64x32px, |
| | **TEXTURE_PIXEL_SIZE** = :code:`vec2(1/64, 1/32)` |
+--------------------------------+------------------------------------------------------------------------------+
| in vec2 **SCREEN_UV** | **SCREEN_TEXTURE** Coordinate (for using with screen texture). |
@@ -27,19 +27,19 @@ objects in Godot, while :ref:`Spatial <doc_spatial_shader>` shaders are used
to draw all 3D objects.
In order to use a shader it must be attached inside a :ref:`Material
<class_material>` which must be attached to an object. Materials are a type of
<class_Material>` which must be attached to an object. Materials are a type of
:ref:`Resource <doc_resources>`. To draw multiple objects with the same
material, the material must be attached to each object.
All objects derived from a :ref:`CanvasItem <class_canvasitem>` have a material
property. This includes all :ref:`GUI elements <class_Control>`, :ref:`Sprites
<class_sprite>`, :ref:`TileMaps <class_tilemap>`, :ref:`MeshInstance2Ds
<class_meshinstance2d>` etc. They also have an option to inherit their parent's
All objects derived from a :ref:`CanvasItem <class_CanvasItem>` have a material
property. This includes all :ref:`GUI elements <class_Control>`, :ref:`Sprite2Ds
<class_Sprite2D>`, :ref:`TileMaps <class_Tilemap>`, :ref:`MeshInstance2Ds
<class_MeshInstance2D>` etc. They also have an option to inherit their parent's
material. This can be useful if you have a large number of nodes that you want
to use the same material.
To begin, create a Sprite node. You can use any CanvasItem, but for this
tutorial we will use a Sprite.
To begin, create a Sprite2D node. You can use any CanvasItem, but for this
tutorial we will use a Sprite2D.
In the Inspector, click beside "Texture" where it says "[empty]" and select
"Load", then select "Icon.png". For new projects, this is the Godot icon. You
@@ -81,11 +81,11 @@ covered here.
Your first fragment function
----------------------------
The fragment function runs for every pixel in a Sprite and determines what color
The fragment function runs for every pixel in a Sprite2D and determines what color
that pixel should be.
They are restricted to the pixels covered by the Sprite, that means you cannot
use one to, for example, create an outline around a Sprite.
They are restricted to the pixels covered by the Sprite2D, that means you cannot
use one to, for example, create an outline around a Sprite2D.
The most basic fragment function does nothing except assign a single color to
every pixel.
@@ -109,7 +109,7 @@ Godot.
Now let's make things more complex.
There are many inputs to the fragment function that you can use for calculating
``COLOR``. ``UV`` is one of them. UV coordinates are specified in your Sprite
``COLOR``. ``UV`` is one of them. UV coordinates are specified in your Sprite2D
(without you knowing it!) and they tell the shader where to read from textures
for each part of the mesh.
@@ -131,7 +131,7 @@ other functions or to assign values to ``COLOR`` directly.
Using ``TEXTURE`` built-in
^^^^^^^^^^^^^^^^^^^^^^^^^^
When you want to adjust a color in a Sprite you cannot just adjust the color
When you want to adjust a color in a Sprite2D you cannot just adjust the color
from the texture manually like in the code below.
.. code-block:: glsl
@@ -144,9 +144,9 @@ from the texture manually like in the code below.
The default fragment function reads from a texture and displays it. When you
overwrite the default fragment function, you lose that functionality, so you
have to implement it yourself. You read from textures using the ``texture``
function. Certain nodes, like Sprites, have a dedicated texture variable that
function. Certain nodes, like Sprite2Ds, have a dedicated texture variable that
can be accessed in the shader using ``TEXTURE``. Use it together with ``UV`` and
``texture`` to draw the Sprite.
``texture`` to draw the Sprite2D.
.. code-block:: glsl
@@ -172,7 +172,7 @@ You can use uniforms by defining them at the top of your shader like so:
For more information about usage see the :ref:`Shading Language doc
<doc_shading_language>`.
Add a uniform to change the amount of blue in our Sprite.
Add a uniform to change the amount of blue in our Sprite2D.
.. code-block:: glsl
@@ -183,7 +183,7 @@ Add a uniform to change the amount of blue in our Sprite.
COLOR.b = blue;
}
Now you can change the amount of blue in the Sprite from the editor. Look back
Now you can change the amount of blue in the Sprite2D from the editor. Look back
at the Inspector under where you created your shader. You should see a section
called "Shader Param". Unfold that section and you will see the uniform you just
declared. If you change the value in the editor, it will overwrite the default
@@ -193,7 +193,7 @@ Interacting with shaders from code
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can change uniforms from code using the function ``set_shader_param()``
which is called on the node's material resource. With a Sprite node, the
which is called on the node's material resource. With a Sprite2D node, the
following code can be used to set the ``blue`` uniform.
::
@@ -232,7 +232,7 @@ animation.
.. code-block:: glsl
void vertex() {
// Animate Sprite moving in big circle around its location
// Animate Sprite2D moving in big circle around its location
VERTEX += vec2(cos(TIME)*100.0, sin(TIME)*100.0);
}