Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
RigidBody3D
Hereda: PhysicsBody3D < CollisionObject3D < Node3D < Node < Object
Heredado por: VehicleBody3D
Un cuerpo físico 3D que se mueve mediante una simulación física.
Descripción
RigidBody3D implements full 3D physics. It cannot be controlled directly, instead, you must apply forces to it (gravity, impulses, etc.), and the physics simulation will calculate the resulting movement, rotation, react to collisions, and affect other physics bodies in its path.
The body's behavior can be adjusted via lock_rotation, freeze, and freeze_mode. By changing various properties of the object, such as mass, you can control how the physics simulation acts on it.
A rigid body will always maintain its shape and size, even when forces are applied to it. It is useful for objects that can be interacted with in an environment, such as a tree that can be knocked over or a stack of crates that can be pushed around.
If you need to directly affect the body, prefer _integrate_forces() as it allows you to directly access the physics state.
If you need to override the default physics behavior, you can write a custom force integration function. See custom_integrator.
Note: Changing the 3D transform or linear_velocity of a RigidBody3D very often may lead to some unpredictable behaviors. This also happens when a RigidBody3D is the descendant of a constantly moving node, like another RigidBody3D, as that will cause its global transform to be set whenever its ancestor moves.
Tutoriales
Propiedades
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
Métodos
void |
_integrate_forces(state: PhysicsDirectBodyState3D) virtual |
void |
add_constant_central_force(force: Vector3) |
void |
add_constant_force(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) |
void |
add_constant_torque(torque: Vector3) |
void |
apply_central_force(force: Vector3) |
void |
apply_central_impulse(impulse: Vector3) |
void |
apply_force(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) |
void |
apply_impulse(impulse: Vector3, position: Vector3 = Vector3(0, 0, 0)) |
void |
apply_torque(torque: Vector3) |
void |
apply_torque_impulse(impulse: Vector3) |
get_colliding_bodies() const |
|
get_contact_count() const |
|
get_inverse_inertia_tensor() const |
|
void |
set_axis_velocity(axis_velocity: Vector3) |
Señales
Se emite cuando ocurre una colisión con otro PhysicsBody3D o GridMap. Requiere que contact_monitor esté establecido en true y que max_contacts_reported sea lo suficientemente alto para detectar todas las colisiones. Los GridMaps se detectan si la MeshLibrary tiene formas de colisión Shape3D.
body el Node, si existe en el árbol, del otro PhysicsBody3D o GridMap.
Se emite cuando la colisión con otro PhysicsBody3D o GridMap finaliza. Requiere que contact_monitor esté establecido en true y que max_contacts_reported sea lo suficientemente alto para detectar todas las colisiones. Los GridMaps se detectan si la MeshLibrary tiene formas de colisión Shape3D.
body el Node, si existe en el árbol, del otro PhysicsBody3D o GridMap.
body_shape_entered(body_rid: RID, body: Node, body_shape_index: int, local_shape_index: int) 🔗
Emitted when one of this RigidBody3D's Shape3Ds collides with another PhysicsBody3D or GridMap's Shape3Ds. Requires contact_monitor to be set to true and max_contacts_reported to be set high enough to detect all the collisions. GridMaps are detected if the MeshLibrary has Collision Shape3Ds.
body_rid the RID of the other PhysicsBody3D or MeshLibrary's CollisionObject3D used by the PhysicsServer3D.
body the Node, if it exists in the tree, of the other PhysicsBody3D or GridMap.
body_shape_index the index of the Shape3D of the other PhysicsBody3D or GridMap used by the PhysicsServer3D. Get the CollisionShape3D node with body.shape_owner_get_owner(body.shape_find_owner(body_shape_index)).
local_shape_index the index of the Shape3D of this RigidBody3D used by the PhysicsServer3D. Get the CollisionShape3D node with self.shape_owner_get_owner(self.shape_find_owner(local_shape_index)).
body_shape_exited(body_rid: RID, body: Node, body_shape_index: int, local_shape_index: int) 🔗
Emitted when the collision between one of this RigidBody3D's Shape3Ds and another PhysicsBody3D or GridMap's Shape3Ds ends. Requires contact_monitor to be set to true and max_contacts_reported to be set high enough to detect all the collisions. GridMaps are detected if the MeshLibrary has Collision Shape3Ds.
body_rid the RID of the other PhysicsBody3D or MeshLibrary's CollisionObject3D used by the PhysicsServer3D. GridMaps are detected if the Meshes have Shape3Ds.
body the Node, if it exists in the tree, of the other PhysicsBody3D or GridMap.
body_shape_index the index of the Shape3D of the other PhysicsBody3D or GridMap used by the PhysicsServer3D. Get the CollisionShape3D node with body.shape_owner_get_owner(body.shape_find_owner(body_shape_index)).
local_shape_index the index of the Shape3D of this RigidBody3D used by the PhysicsServer3D. Get the CollisionShape3D node with self.shape_owner_get_owner(self.shape_find_owner(local_shape_index)).
sleeping_state_changed() 🔗
Emitida cuando el motor físico cambia el estado de sueño del cuerpo.
Nota: Cambiar el valor sleeping no activará esta señal. Solo se emite si el motor de física cambia el estado de sueño o si se utiliza emit_signal("sleeping_state_changed").
Enumeraciones
enum FreezeMode: 🔗
FreezeMode FREEZE_MODE_STATIC = 0
Modo de congelación estática del cuerpo (predeterminado). El cuerpo no se ve afectado por la gravedad ni las fuerzas. Solo se puede mover mediante código de usuario y no colisiona con otros cuerpos en su trayectoria.
FreezeMode FREEZE_MODE_KINEMATIC = 1
Modo de congelación cinemática de cuerpos. Similar a FREEZE_MODE_STATIC, pero colisiona con otros cuerpos en su trayectoria al moverse. Útil para cuerpos congelados que necesitan ser animados.
enum CenterOfMassMode: 🔗
CenterOfMassMode CENTER_OF_MASS_MODE_AUTO = 0
En este modo, el centro de masa del cuerpo se calcula automáticamente a partir de sus formas. Esto supone que el origen de las formas también es su centro de masa.
CenterOfMassMode CENTER_OF_MASS_MODE_CUSTOM = 1
En este modo, el centro de masa del cuerpo se establece a través de center_of_mass. El valor predeterminado es la posición de origen del cuerpo.
enum DampMode: 🔗
DampMode DAMP_MODE_COMBINE = 0
En este modo, el valor de amortiguación del cuerpo se añade a cualquier valor establecido en las áreas o al valor predeterminado.
DampMode DAMP_MODE_REPLACE = 1
En este modo, el valor de amortiguación del cuerpo reemplaza cualquier valor establecido en las áreas o al valor predeterminado.
Descripciones de Propiedades
Amortigua la rotación del cuerpo. Por defecto, el cuerpo utilizará el ajuste del proyecto ProjectSettings.physics/3d/default_angular_damp o cualquier valor de anulación establecido por un Area3D en el que se encuentre el cuerpo. Dependiendo de angular_damp_mode, puedes configurar angular_damp para que se añada o reemplace el valor de amortiguación del cuerpo.
Véase ProjectSettings.physics/3d/default_angular_damp para más detalles sobre la amortiguación.
DampMode angular_damp_mode = 0 🔗
Define cómo se aplica angular_damp.
Vector3 angular_velocity = Vector3(0, 0, 0) 🔗
The RigidBody3D's rotational velocity in radians per second.
If true, the body can enter sleep mode when there is no movement. See sleeping.
Vector3 center_of_mass = Vector3(0, 0, 0) 🔗
The body's custom center of mass, relative to the body's origin position, when center_of_mass_mode is set to CENTER_OF_MASS_MODE_CUSTOM. This is the balanced point of the body, where applied forces only cause linear acceleration. Applying forces outside of the center of mass causes angular acceleration.
When center_of_mass_mode is set to CENTER_OF_MASS_MODE_AUTO (default value), the center of mass is automatically determined, but this does not update the value of center_of_mass.
CenterOfMassMode center_of_mass_mode = 0 🔗
void set_center_of_mass_mode(value: CenterOfMassMode)
CenterOfMassMode get_center_of_mass_mode()
Define la forma en que se establece el centro de masa del cuerpo.
Vector3 constant_force = Vector3(0, 0, 0) 🔗
The body's total constant positional forces applied during each physics update.
See add_constant_force() and add_constant_central_force().
Vector3 constant_torque = Vector3(0, 0, 0) 🔗
The body's total constant rotational forces applied during each physics update.
bool contact_monitor = false 🔗
If true, the RigidBody3D will emit signals when it collides with another body.
Note: By default the maximum contacts reported is set to 0, meaning nothing will be recorded, see max_contacts_reported.
void set_use_continuous_collision_detection(value: bool)
bool is_using_continuous_collision_detection()
Si es true, se utiliza la detección continua de colisiones.
La detección de colisión continua trata de predecir dónde colisionará un cuerpo en movimiento, en lugar de moverlo y corregir su movimiento si colisionara. La detección de colisión continua es más precisa, y pierde menos impactos de objetos pequeños y de movimiento rápido. No usar la detección de colisión continua es más rápido de calcular, pero puede pasar por alto los objetos pequeños y de movimiento rápido.
bool custom_integrator = false 🔗
Si es true, la integración estándar de fuerzas (como la gravedad o la amortiguación) se deshabilitará para este cuerpo. Aparte de la respuesta a la colisión, el cuerpo solo se moverá según lo determinado por el método _integrate_forces(), si ese método virtual es sobrescrito.
Establecer esta propiedad llamará internamente al método PhysicsServer3D.body_set_omit_force_integration().
If true, the body is frozen. Gravity and forces are not applied anymore.
See freeze_mode to set the body's behavior when frozen.
Note: For a body that is always frozen, use StaticBody3D or AnimatableBody3D instead.
FreezeMode freeze_mode = 0 🔗
void set_freeze_mode(value: FreezeMode)
FreezeMode get_freeze_mode()
The body's freeze mode. Determines the body's behavior when freeze is true.
Note: For a body that is always frozen, use StaticBody3D or AnimatableBody3D instead.
Esto se multiplica por ProjectSettings.physics/3d/default_gravity para producir la gravedad de este cuerpo. Por ejemplo, un valor de 1.0 aplicará la gravedad normal, 2.0 aplicará el doble de gravedad y 0.5 aplicará la mitad de gravedad a este cuerpo.
Vector3 inertia = Vector3(0, 0, 0) 🔗
The body's moment of inertia. This is like mass, but for rotation: it determines how much torque it takes to rotate the body on each axis. The moment of inertia is usually computed automatically from the mass and the shapes, but this property allows you to set a custom value.
If set to Vector3.ZERO, inertia is automatically computed (default value).
Note: This value does not change when inertia is automatically computed. Use PhysicsServer3D to get the computed inertia.
@onready var ball = $Ball
func get_ball_inertia():
return PhysicsServer3D.body_get_direct_state(ball.get_rid()).inverse_inertia.inverse()
private RigidBody3D _ball;
public override void _Ready()
{
_ball = GetNode<RigidBody3D>("Ball");
}
private Vector3 GetBallInertia()
{
return PhysicsServer3D.BodyGetDirectState(_ball.GetRid()).InverseInertia.Inverse();
}
Damps the body's movement. By default, the body will use the ProjectSettings.physics/3d/default_linear_damp project setting or any value override set by an Area3D the body is in. Depending on linear_damp_mode, you can set linear_damp to be added to or to replace the body's damping value.
See ProjectSettings.physics/3d/default_linear_damp for more details about damping.
DampMode linear_damp_mode = 0 🔗
Define cómo se aplica linear_damp.
Vector3 linear_velocity = Vector3(0, 0, 0) 🔗
The body's linear velocity in units per second. Can be used sporadically, but don't set this every frame, because physics may run in another thread and runs at a different granularity. Use _integrate_forces() as your process loop for precise control of the body state.
If true, the body cannot rotate. Gravity and forces only apply linear movement.
La masa del cuerpo.
int max_contacts_reported = 0 🔗
The maximum number of contacts that will be recorded. Requires a value greater than 0 and contact_monitor to be set to true to start to register contacts. Use get_contact_count() to retrieve the count or get_colliding_bodies() to retrieve bodies that have been collided with.
Note: The number of contacts is different from the number of collisions. Collisions between parallel edges will result in two contacts (one at each end), and collisions between parallel faces will result in four contacts (one at each corner).
PhysicsMaterial physics_material_override 🔗
void set_physics_material_override(value: PhysicsMaterial)
PhysicsMaterial get_physics_material_override()
El material de la física se sobrescribe para el cuerpo.
Si se asigna un material a esta propiedad, se utilizará en lugar de cualquier otro material de física, como por ejemplo uno heredado.
If true, the body will not move and will not calculate forces until woken up by another body through, for example, a collision, or by using the apply_impulse() or apply_force() methods.
Descripciones de Métodos
void _integrate_forces(state: PhysicsDirectBodyState3D) virtual 🔗
Called during physics processing, allowing you to read and safely modify the simulation state for the object. By default, it is called before the standard force integration, but the custom_integrator property allows you to disable the standard force integration and do fully custom force integration for a body.
void add_constant_central_force(force: Vector3) 🔗
Añade una fuerza direccional constante sin afectar la rotación que se aplica continuamente hasta que se elimina con constant_force = Vector3(0, 0, 0).
Esto es equivalente a usar add_constant_force() en el centro de masa del cuerpo.
void add_constant_force(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) 🔗
Añade una fuerza posicionada constante al cuerpo que se aplica continuamente hasta que se elimina con constant_force = Vector3(0, 0, 0).
position es el desplazamiento desde el origen del cuerpo en coordenadas globales.
void add_constant_torque(torque: Vector3) 🔗
Añade una fuerza rotacional constante sin afectar la posición, que se aplica continuamente hasta que se elimina con constant_torque = Vector3(0, 0, 0).
void apply_central_force(force: Vector3) 🔗
Aplica una fuerza direccional sin afectar la rotación. Una fuerza depende del tiempo y está pensada para ser aplicada en cada actualización de la física.
Esto es equivalente a usar apply_force() en el centro de masa del cuerpo.
void apply_central_impulse(impulse: Vector3) 🔗
Aplica un impulso direccional sin afectar la rotación.
¡Un impulso es independiente del tiempo! Aplicar un impulso en cada fotograma resultaría en una fuerza dependiente de la velocidad de fotogramas. Por esta razón, solo debe usarse al simular impactos únicos (usa las funciones "_force" en su lugar).
Esto es equivalente a usar apply_impulse() en el centro de masa del cuerpo.
void apply_force(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) 🔗
Aplica una fuerza posicionada al cuerpo. Una fuerza depende del tiempo y está pensada para ser aplicada en cada actualización de la física.
position es el desplazamiento desde el origen del cuerpo en coordenadas globales.
void apply_impulse(impulse: Vector3, position: Vector3 = Vector3(0, 0, 0)) 🔗
Aplica un impulso posicionado al cuerpo.
¡Un impulso es independiente del tiempo! Aplicar un impulso en cada fotograma resultaría en una fuerza dependiente de la velocidad de fotogramas. Por esta razón, solo debe usarse al simular impactos únicos (usa las funciones "_force" en su lugar).
position es el desplazamiento desde el origen del cuerpo en coordenadas globales.
void apply_torque(torque: Vector3) 🔗
Applies a rotational force without affecting position. A force is time dependent and meant to be applied every physics update.
Note: inertia is required for this to work. To have inertia, an active CollisionShape3D must be a child of the node, or you can manually set inertia.
void apply_torque_impulse(impulse: Vector3) 🔗
Applies a rotational impulse to the body without affecting the position.
An impulse is time-independent! Applying an impulse every frame would result in a framerate-dependent force. For this reason, it should only be used when simulating one-time impacts (use the "_force" functions otherwise).
Note: inertia is required for this to work. To have inertia, an active CollisionShape3D must be a child of the node, or you can manually set inertia.
Array[Node3D] get_colliding_bodies() const 🔗
Returns a list of the bodies colliding with this one. Requires contact_monitor to be set to true and max_contacts_reported to be set high enough to detect all the collisions.
Note: The result of this test is not immediate after moving objects. For performance, list of collisions is updated once per frame and before the physics step. Consider using signals instead.
int get_contact_count() const 🔗
Returns the number of contacts this body has with other bodies. By default, this returns 0 unless bodies are configured to monitor contacts (see contact_monitor).
Note: To retrieve the colliding bodies, use get_colliding_bodies().
Basis get_inverse_inertia_tensor() const 🔗
Returns the inverse inertia tensor basis. This is used to calculate the angular acceleration resulting from a torque applied to the RigidBody3D.
void set_axis_velocity(axis_velocity: Vector3) 🔗
Establece una velocidad del eje. La velocidad en el eje vectorial dado se fijará como la longitud del vector dado. Esto es útil para el comportamiento de salto.