Up to date

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

Introducción al 3D

Creating a 3D game can be challenging. That extra Z coordinate makes many of the common techniques that helped to make 2D games simpler no longer work. To aid in this transition, it is worth mentioning that Godot uses similar APIs for 2D and 3D. Most nodes are the same and are present in both 2D and 3D versions. In fact, it is worth checking the 3D platformer tutorial, or the 3D kinematic character tutorials, which are almost identical to their 2D counterparts.

En 3D las matemáticas son un poco más complejas que en 2D, así que revisar la sección Matemáticas vectoriales de la wiki (que fue creada especialmente para desarrolladores de juegos, no para matemáticos o ingenieros) ayudará a allanar el camino hacia el desarrollo eficiente de juegos 3D.

Node3D node

Node2D is the base node for 2D. Control is the base node for everything GUI. Following this reasoning, the 3D engine uses the Node3D node for everything 3D.

Nota

Be aware that "Spatial" Nodes are now called "Node3D" starting with Godot 4. Any Godot 3.x references to "Spatial" Nodes refer to "Node3D" in Godot 4.

../../_images/tuto_3d1.png

Node3Ds have a local transform, which is relative to the parent node (as long as the parent node is also of or inherits from the type Node3D). This transform can be accessed as a 4×3 Transform3D, or as 3 Vector3 members representing location, Euler rotation (X, Y and Z angles) and scale.

../../_images/tuto_3d2.png

Contenido 3D

Unlike 2D, where loading image content and drawing is straightforward, 3D is a little more difficult. The content needs to be created with special 3D tools (also called Digital Content Creation tools, or DCCs) and exported to an exchange file format to be imported in Godot. This is required since 3D formats are not as standardized as images.

Manually authored models (using 3D modeling software)

There are two pipelines to import 3D models in Godot. The first and most common one is by Importando escenas 3D, which allows you to import entire scenes (exactly as they look in the 3D modeling software), including animation, skeletal rigs, blend shapes, etc.

The second pipeline is by importing simple .OBJ files as mesh resources, which can be then put inside a MeshInstance3D node for display.

Geometría generada

Es posible crear geometría personalizada usando el recurso ArrayMesh directamente. Simplemente crea tus arrays y usa la función ArrayMesh.add_surface_from_arrays(). También está disponible una clase de utilidad, SurfaceTool, que proporciona una API más sencilla y ayuda para indexar, generar normales, tangentes, etc.

En cualquier caso, este método está destinado a generar geometría estática (modelos que no se actualizarán con frecuencia), ya que la creación de arrays de vértices y su envío a la API 3D tiene un coste de rendimiento significativo.

Geometría inmediata

If, instead, you need to generate simple geometry that will be updated often, Godot provides a special ImmediateMesh resource that can be used in a MeshInstance3D node. This provides an OpenGL 1.x-style immediate-mode API to create points, lines, triangles, etc.

2D en 3D

Mientras que Godot cuenta con un potente motor 2D, muchos tipos de juegos utilizan 2D en un entorno 3D. Utilizando una cámara fija (ya sea ortogonal o perspectiva) que no gira, nodos como Sprite3D y AnimatedSprite3D pueden ser usados para crear juegos 2D que se aprovechan de la mezcla con fondos 3D, parallax más realistas, efectos de iluminación/sombra, etc.

La desventaja es, por supuesto, que la complejidad añadida y el rendimiento reducido en comparación con 2D simple, así como la falta de referencia de trabajo en píxeles.

Entorno

Además de editar una escena, a menudo es común editar el entorno. Godot proporciona un nodo WorldEnvironment que permite cambiar el color de fondo, el modo (como por ejemplo, poner un skybox), y aplicar varios tipos de efectos de post-procesamiento incorporados. Los entornos también se pueden anular en la cámara.

Vista 3D

Editing 3D scenes is done in the 3D tab. This tab can be selected manually, but it will be automatically enabled when a Node3D node is selected.

../../_images/tuto_3d3.png

Los controles de navegación de escena 3D predeterminados son similares a Blender (con el objetivo de tener algún tipo de consistencia entre software libre usado para el desarrollo...), pero se incluyen opciones para personalizar los botones y el comportamiento del mouse para que sean similares a otras herramientas en Ajustes del Editor:

../../_images/tuto_3d4.png

Sistema de coordenadas

Godot utiliza el sistema métrico para todo en 3D, donde 1 unidad equivale a 1 metro. La física y otras áreas están ajustadas para esta escala. Por lo tanto, intentar utilizar una escala diferente generalmente es una mala idea (a menos que sepas lo que estás haciendo).

When working with 3D assets, it's always best to work in the correct scale (set the unit to metric in your 3D modeling software). Godot allows scaling post-import and, while this works in most cases, in rare situations it may introduce floating-point precision issues (and thus, glitches or artifacts) in delicate areas such as rendering or physics. Make sure your artists always work in the right scale!

The Y coordinate is used for "up". As for the horizontal X/Z axes, Godot uses a right-handed coordinate system. This means that for most objects that need alignment (such as lights or cameras), the Z axis is used as a "pointing towards" direction. This convention roughly means that:

  • X es los lados

  • Y es arriba/abajo

  • Z es adelante/atrás

See this chart for comparison with other 3D software:

3D coordinate systems comparison chart

Image by Freya Holmér

Gizmos de espacio y manipulación

El movimiento de objetos en la vista 3D se realiza a través de los gizmos del manipulación. Cada eje está representado por un color: Rojo, Verde, Azul representan X, Y, Z respectivamente. Esta convención se aplica también a la cuadrícula y a otros gizmos (y también al lenguaje de shaders, el orden de los componentes para Vector3, Color, etc.).

../../_images/tuto_3d5.png

Algunos keybindings útiles:

  • Para ajustar el movimiento o la rotación, presiona la tecla Ctrl mientras estás moviendo, escalando o rotando.

  • Para centrar la vista en el objeto seleccionado, presiona F.

Using Blender-style transform shortcuts

Since Godot 4.2, you can enable Blender-style shortcuts for translating, rotating and scaling nodes. In Blender, these shortcuts are:

  • G for translating

  • R for rotating

  • S for scaling

After pressing a shortcut key while focusing on the 3D editor viewport, move the mouse or enter a number to move the selected node(s) by the specified amount in 3D units. You can constrain movement to a specific axis by specifying the axis as a letter, then the distance (if entering a value with the keyboard).

For instance, to move the selection upwards by 2.5 units, enter the following sequence in order (Y+ is upwards in Godot):

G-Y-2-.-5-Enter

To use Blender-style transform shortcuts in Godot, go to the Editor Settings' Shortcuts tab, then in the Spatial Editor section:

  • Bind Begin Translate Transformation to G.

  • Bind Begin Rotate Transformation to R.

  • Bind Begin Scale Transformation to S.

  • Finally, unbind Scale Mode so that its shortcut won't conflict with Begin Rotate Transformation.

Menú Ver

Las opciones de visualización se controlan mediante el menú "Ver" en la barra de herramientas la vista 3D.

../../_images/tuto_3d6.png

Puedes ocultar los artilugios en la vista 3D del editor a través de este menú:

../../_images/tuto_3d6_1.png

Para ocultar un tipo específico de instrumentos, puedes desactivarlos en el menú "Ver".

../../_images/tuto_3d6_2.png

Entorno por defecto

Cuando se crea desde el Administrador de Proyectos, el entorno 3D tiene un cielo por defecto.

../../_images/tuto_3d8.png

Given how physically-based rendering works, it is advised to always try to work with a default environment in order to provide indirect and reflected light to your objects.

Cámaras

No matter how many objects are placed in the 3D space, nothing will be displayed unless a Camera3D is also added to the scene. Cameras can work in either orthogonal or perspective projections:

../../_images/tuto_3d10.png

Las cámaras están asociadas y sólo se muestran en el Viewport de un padre o abuelo. Dado que la raíz del árbol de escenas es un viewport, las cámaras se mostrarán en él de forma predeterminada, pero si se desean sub-viewports (ya sea como objetivo de render o como imagen-en-imagen), estos necesitan sus propias cámaras hijas para que se muestre su contenido.

../../_images/tuto_3d11.png

Cuando se trata de varias cámaras, se siguen las siguientes reglas para cada viewport:

  • Si no hay cámaras en el árbol de escenas, la primera que entre en él se convertirá en la cámara activa. Otras cámaras que entren en la escena serán ignoradas (a menos que estén configuradas como actual).

  • Si una cámara tiene la propiedad "actual" establecida, se utilizará independientemente de cualquier otra cámara de la escena. Si la propiedad está configurada, se activará, sustituyendo a la cámara anterior.

  • Si una cámara activa deja el árbol de escena, la primera cámara en orden de árbol tomará su lugar.

Luces

The background environment emits some ambient light which appears on surfaces. Still, without any light sources placed in the scene, the scene will appear quite dark unless the background environment is very bright.

Most outdoor scenes have a directional light (the sun or moon), while indoor scenes typically have several positional lights (lamps, torches, …). See Luces y sombras 3D for more information on setting up lights in Godot.