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...
RigidBody2D¶
Inherits: PhysicsBody2D < CollisionObject2D < Node2D < CanvasItem < Node < Object
Un cuerpo que es controlado por el motor de física 2D.
Descripción¶
This node implements simulated 2D physics. You do not control a RigidBody2D directly. Instead, you apply forces to it (gravity, impulses, etc.) and the physics simulation calculates the resulting movement based on its mass, friction, and other physical properties.
A RigidBody2D has 4 behavior modes: Rigid, Static, Character, and Kinematic.
Note: You should not change a RigidBody2D's position
or linear_velocity
every frame or even very often. If you need to directly affect the body's state, use _integrate_forces, which allows you to directly access the physics state.
Please also keep in mind that physics bodies manage their own transform which overwrites the ones you set. So any direct or indirect transformation (including scaling of the node or its parent) will be visible in the editor only, and immediately reset at runtime.
If you need to override the default physics behavior or add a transformation at runtime, you can write a custom force integration. See custom_integrator.
The center of mass is always located at the node's origin without taking into account the CollisionShape2D centroid offsets.
Tutoriales¶
Propiedades¶
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
Métodos¶
void |
_integrate_forces ( Physics2DDirectBodyState state ) virtual |
void |
add_central_force ( Vector2 force ) |
void |
|
void |
add_torque ( float torque ) |
void |
apply_central_impulse ( Vector2 impulse ) |
void |
apply_impulse ( Vector2 offset, Vector2 impulse ) |
void |
apply_torque_impulse ( float torque ) |
get_colliding_bodies ( ) const |
|
void |
set_axis_velocity ( Vector2 axis_velocity ) |
test_motion ( Vector2 motion, bool infinite_inertia=true, float margin=0.08, Physics2DTestMotionResult result=null ) |
Señales¶
body_entered ( Node body )
Emitted when a collision with another PhysicsBody2D or TileMap occurs. Requires contact_monitor to be set to true
and contacts_reported to be set high enough to detect all the collisions. TileMaps are detected if the TileSet has Collision Shape2Ds.
body
the Node, if it exists in the tree, of the other PhysicsBody2D or TileMap.
body_exited ( Node body )
Emitted when the collision with another PhysicsBody2D or TileMap ends. Requires contact_monitor to be set to true
and contacts_reported to be set high enough to detect all the collisions. TileMaps are detected if the TileSet has Collision Shape2Ds.
body
the Node, if it exists in the tree, of the other PhysicsBody2D or TileMap.
Emitted when one of this RigidBody2D's Shape2Ds collides with another PhysicsBody2D or TileMap's Shape2Ds. Requires contact_monitor to be set to true
and contacts_reported to be set high enough to detect all the collisions. TileMaps are detected if the TileSet has Collision Shape2Ds.
body_rid
the RID of the other PhysicsBody2D or TileSet's CollisionObject2D used by the Physics2DServer.
body
the Node, if it exists in the tree, of the other PhysicsBody2D or TileMap.
body_shape_index
the index of the Shape2D of the other PhysicsBody2D or TileMap used by the Physics2DServer. Get the CollisionShape2D node with body.shape_owner_get_owner(body_shape_index)
.
local_shape_index
the index of the Shape2D of this RigidBody2D used by the Physics2DServer. Get the CollisionShape2D node with self.shape_owner_get_owner(local_shape_index)
.
Emitted when the collision between one of this RigidBody2D's Shape2Ds and another PhysicsBody2D or TileMap's Shape2Ds ends. Requires contact_monitor to be set to true
and contacts_reported to be set high enough to detect all the collisions. TileMaps are detected if the TileSet has Collision Shape2Ds.
body_rid
the RID of the other PhysicsBody2D or TileSet's CollisionObject2D used by the Physics2DServer.
body
the Node, if it exists in the tree, of the other PhysicsBody2D or TileMap.
body_shape_index
the index of the Shape2D of the other PhysicsBody2D or TileMap used by the Physics2DServer. Get the CollisionShape2D node with body.shape_owner_get_owner(body_shape_index)
.
local_shape_index
the index of the Shape2D of this RigidBody2D used by the Physics2DServer. Get the CollisionShape2D node with self.shape_owner_get_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. Sólo 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 Mode:
MODE_RIGID = 0 --- Modo rígido. El cuerpo se comporta como un objeto físico. Colisiona con otros cuerpos y responde a las fuerzas que se le aplican. Este es el modo por defecto.
MODE_STATIC = 1 --- Modo estático. El cuerpo se comporta como un StaticBody2D y no se mueve.
MODE_CHARACTER = 2 --- Modo de personaje. Similar a MODE_RIGID, pero el cuerpo no puede rotar.
MODE_KINEMATIC = 3 --- Modo cinemático. El cuerpo se comporta como un KinematicBody2D, y debe ser movido por un código.
enum CCDMode:
CCD_MODE_DISABLED = 0 --- Detección de colisión continua desactivada. Es la forma más rápida de detectar colisiones corporales, pero puede pasar por alto pequeños objetos de movimiento rápido.
CCD_MODE_CAST_RAY = 1 --- Detección de colisión continua activada mediante raycasting. Esto es más rápido que el "shapecasting" pero menos preciso.
CCD_MODE_CAST_SHAPE = 2 --- Detección de colisión continua habilitada mediante el uso de "shapecasting". Este es el método CCD más lento y más preciso.
Descripciones de Propiedades¶
float angular_damp
Default |
|
Setter |
set_angular_damp(value) |
Getter |
get_angular_damp() |
Damps the body's angular_velocity. If -1
, the body will use the Default Angular Damp defined in Project > Project Settings > Physics > 2d.
See ProjectSettings.physics/2d/default_angular_damp for more details about damping.
float angular_velocity
Default |
|
Setter |
set_angular_velocity(value) |
Getter |
get_angular_velocity() |
The body's rotational velocity in radians per second.
Vector2 applied_force
Default |
|
Setter |
set_applied_force(value) |
Getter |
get_applied_force() |
La fuerza total aplicada al cuerpo.
float applied_torque
Default |
|
Setter |
set_applied_torque(value) |
Getter |
get_applied_torque() |
El torque total aplicado al cuerpo.
float bounce
Setter |
set_bounce(value) |
Getter |
get_bounce() |
The body's bounciness. Values range from 0
(no bounce) to 1
(full bounciness).
Deprecated, use PhysicsMaterial.bounce instead via physics_material_override.
bool can_sleep
Default |
|
Setter |
set_can_sleep(value) |
Getter |
is_able_to_sleep() |
If true
, the body can enter sleep mode when there is no movement. See sleeping.
Note: A RigidBody2D will never enter sleep mode automatically if its mode is MODE_CHARACTER. It can still be put to sleep manually by setting its sleeping property to true
.
bool contact_monitor
Default |
|
Setter |
set_contact_monitor(value) |
Getter |
is_contact_monitor_enabled() |
Si es true
, el cuerpo emitirá señales cuando colisione con otro RigidBody2D. Véase tambien contacts_reported.
int contacts_reported
Default |
|
Setter |
set_max_contacts_reported(value) |
Getter |
get_max_contacts_reported() |
The maximum number of contacts that will be recorded. Requires contact_monitor to be set to true
.
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).
CCDMode continuous_cd
Default |
|
Setter |
set_continuous_collision_detection_mode(value) |
Getter |
get_continuous_collision_detection_mode() |
Modo de detección de colisiones continua.
La detección de colisiones continua intenta predecir dónde colisionará un cuerpo en movimiento en lugar de moverlo y corregir su movimiento después de la colisión. La detección continua es más lenta, pero más precisa y desacierta menos colisiones con objetos pequeños y en rápido movimiento. Métodos para raycasting y shapecasting están disponibles. Véase CCDMode para más detalles.
bool custom_integrator
Default |
|
Setter |
set_use_custom_integrator(value) |
Getter |
is_using_custom_integrator() |
Si es true
, la integración para fuerzas internas está desabilitada para este cuerpo. Aparte de reaccionar a colisiones, el cuerpo sólo se moverá por la función _integrate_forces.
float friction
Setter |
set_friction(value) |
Getter |
get_friction() |
The body's friction. Values range from 0
(frictionless) to 1
(maximum friction).
Deprecated, use PhysicsMaterial.friction instead via physics_material_override.
float gravity_scale
Default |
|
Setter |
set_gravity_scale(value) |
Getter |
get_gravity_scale() |
Multiplica la gravedad aplicada al cuerpo. La gravedad del cuerpo se calcula a partir del valor Gravedad por defecto en Proyecto > Configuración del proyecto > Física > 2d y/o cualquier vector de gravedad adicional aplicado por Area2Ds.
float inertia
Setter |
set_inertia(value) |
Getter |
get_inertia() |
El momento de inercia del cuerpo. Es como la masa, pero para la rotación: determina la cantidad de torsión que se necesita para girar el cuerpo. El momento de inercia suele calcularse automáticamente a partir de la masa y las formas, pero esta función permite establecer un valor personalizado. Establezca 0 inercia para volver a calcularlo automáticamente.
float linear_damp
Default |
|
Setter |
set_linear_damp(value) |
Getter |
get_linear_damp() |
Damps the body's linear_velocity. If -1
, the body will use the Default Linear Damp in Project > Project Settings > Physics > 2d.
See ProjectSettings.physics/2d/default_linear_damp for more details about damping.
Vector2 linear_velocity
Default |
|
Setter |
set_linear_velocity(value) |
Getter |
get_linear_velocity() |
The body's linear velocity in pixels 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.
float mass
Default |
|
Setter |
set_mass(value) |
Getter |
get_mass() |
La masa del cuerpo.
Mode mode
Default |
|
Setter |
set_mode(value) |
Getter |
get_mode() |
El modo del cuerpo. Vea Mode para los posibles valores.
PhysicsMaterial physics_material_override
Setter |
set_physics_material_override(value) |
Getter |
get_physics_material_override() |
El material de la física se sobreescribe 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.
bool sleeping
Default |
|
Setter |
set_sleeping(value) |
Getter |
is_sleeping() |
Si true
, el cuerpo no se moverá y no calculará fuerzas hasta que sea despertado por otro cuerpo a través de, por ejemplo, una colisión, o utilizando los métodos apply_impulse o add_force.
float weight
Default |
|
Setter |
set_weight(value) |
Getter |
get_weight() |
El peso del cuerpo basado en su masa y el valor Gravedad por defecto en Proyecto > Configuración del proyecto > Física > 2d.
Descripciones de Métodos¶
void _integrate_forces ( Physics2DDirectBodyState state ) virtual
Permite leer y modificar con seguridad el estado de simulación del objeto. Utilízalo en lugar del Node._physics_process si necesitas cambiar directamente la position
del cuerpo o otras propiedades físicas. Por defecto, funciona además del comportamiento físico habitual, pero custom_integrator te permite desactivar el comportamiento por defecto y escribir la integración de fuerza personalizada para un cuerpo.
void add_central_force ( Vector2 force )
Añade una fuerza direccional constante sin afectar a la rotación.
Añade una fuerza posicionada al cuerpo. Tanto la fuerza como el desplazamiento del origen del cuerpo están en coordenadas globales.
void add_torque ( float torque )
Añade una fuerza de rotación constante.
void apply_central_impulse ( Vector2 impulse )
Aplica un impulso direccional sin afectar a la rotación.
Aplica un impulso posicionado al cuerpo. ¡Un impulso es independiente del tiempo! Aplicar un impulso en cada cuadro resultaría en una fuerza dependiente del cuadro. Por esta razón, sólo debe utilizarse cuando se simulan impactos únicos (de lo contrario, utilice las funciones "_force"). La posición utiliza la rotación del sistema de coordenadas globales, pero está centrada en el origen del objeto.
void apply_torque_impulse ( float torque )
Aplica un impulso de rotación al cuerpo.
Array get_colliding_bodies ( ) const
Retorna una lista de los cuerpos que colisionan con éste. Requiere que contact_monitor sea true
, y que contacts_reported sea lo suficientemente alto para detectar todas las colisiones.
Nota: El resultado de esta prueba no es inmediato después de mover los objetos. Para un mejor rendimiento, la lista de superposiciones se actualiza una vez por cuadro y antes del paso de física. Considere la posibilidad de utilizar señales en su lugar.
void set_axis_velocity ( Vector2 axis_velocity )
Asigna la velocidad del cuerpo en el eje dado. La velocidad en el eje del vector será asignada como la longitud del vector. Esto es útil para comportamiento pertinente al salto.
bool test_motion ( Vector2 motion, bool infinite_inertia=true, float margin=0.08, Physics2DTestMotionResult result=null )
Returns true
if a collision would result from moving in the given vector. margin
increases the size of the shapes involved in the collision detection, and result
is an object of type Physics2DTestMotionResult, which contains additional information about the collision (should there be one).