Rigidbody2d unity как работает
Перейти к содержимому

Rigidbody2d unity как работает

  • автор:

Rigidbody 2D

A Rigidbody 2D component places an object under the control of the physics engine. Many concepts familiar from the standard Rigidbody component carry over to Rigidbody 2D; the differences are that in 2D, objects can only move in the XY plane and can only rotate on an axis perpendicular to that plane.

The Rigidbody 2D component appears differently in the Unity Editor depending on which Body Type you have selected. See Body Type, below, to learn more.The Rigidbody 2D component appears differently in the Unity Editor depending on which Body Type you have selected. See Body Type, below, to learn more.

How a Rigidbody 2D works

Usually, the Unity Editor’s Transform component defines how a GameObject (and its child GameObjects) is positioned, rotated and scaled within the Scene. When it is changed, it updates other components, which may update things like where they render or where colliders are positioned. The 2D physics engine is able to move colliders and make them interact with each other, so a method is required for the physics engine to communicate this movement of colliders back to the Transform components. This movement and connection with colliders is what a Rigidbody 2D component is for.

The Rigidbody 2D component overrides the Transform and updates it to a position/rotation defined by the Rigidbody 2D. Note that while you can still override the Rigidbody 2D by modifying the Transform component yourself (because Unity exposes all properties on all components), doing so will cause problems such as GameObjects passing through or into each other, and unpredictable movement.

Any Collider 2D component added to the same GameObject or child GameObject is implicitly attached to that Rigidbody 2D. When a Collider 2D is attached to the Rigidbody 2D, it moves with it. A Collider 2D should never be moved directly using the Transform or any collider offset; the Rigidbody 2D should be moved instead. This offers the best performance and ensures correct collision detection. Collider 2Ds attached to the same Rigidbody 2D won’t collide with each other. This means you can create a set of colliders that act effectively as a single compound collider, all moving and rotating in sync with the Rigidbody 2D.

When designing a Scene, you are free to use a default Rigidbody 2D and start attaching colliders. These colliders allow any other colliders attached to different Rigidbody 2Ds to collide with each other.

Adding a Rigidbody 2D allows a sprite to move in a physically convincing way by applying forces from the scripting API. When the appropriate collider component is also attached to the sprite GameObject, it is affected by collisions with other moving GameObjects. Using physics simplifies many common gameplay mechanics and allows for realistic behavior with minimal coding.

Body Type

The Rigidbody 2D component has a setting at the top labelled Body Type. The option you choose for this affects the other settings available on the component.

There are three options for Body Type; each defines a common and fixed behavior. Any Collider 2D attached to a Rigidbody 2D inherits the Rigidbody 2D’s Body Type. The three options are:

  • Dynamic
  • Kinematic
  • Static

The option you choose defines:

  • Movement (position & rotation) behavior
  • Collider interaction

Note that although Rigidbody 2Ds are often described as colliding with each other, it is the Collider 2Ds attached to each of those bodies which collide. Rigidbody 2Ds cannot collide with each other without colliders.

Changing the Body Type of a Rigidbody 2D can be a tricky process. When a Body Type changes, various mass-related internal properties are recalculated immediately, and all existing contacts for the Collider 2Ds attached to the Rigidbody 2D need to be re-evaluated during the GameObject’s next FixedUpdate. Depending on how many contacts and Collider 2Ds are attached to the body, changing the Body Type can cause variations in performance.

Body Type: Dynamic

A Dynamic Rigidbody 2D is designed to move under simulation. It has the full set of properties available to it such as finite mass and drag, and is affected by gravity and forces. A Dynamic body will collide with every other body type, and is the most interactive of body types. This is the default body type for a Rigidbody 2D, because it is the most common body type for things that need to move. It’s also the most performance-expensive body type, because of its dynamic nature and interactivity with everything around it. All Rigidbody 2D properties are available with this body type.

Do not use the Transform component to set the position or rotation of a Dynamic Rigidbody 2D. The simulation repositions a Dynamic Rigidbody 2D according to its velocity; you can change this directly via forces applied to it by scripts, or indirectly via collisions and gravity.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
Tip: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.
Use Auto Mass Check the box if you want the Rigidbody 2D to automatically detect the GameObject’s mass from its Collider 2D.
Mass Define the mass of the Rigidbody 2D. This is grayed out if you have selected Use Auto Mass.
Linear Drag Коэффициент натяжения влияющий на смещение позиции.
Angular Drag Drag coefficient affecting rotational movement.
Gravity Scale Define the degree to which the GameObject is affected by gravity.
Collision Detection Define how collisions between Collider 2D are detected.
Discrete When you set the Collision Detection to Discrete, GameObjects with Rigidbody 2Ds and Collider 2Ds can overlap or pass through each other during a physics update, if they are moving fast enough. Collision contacts are only generated at the new position.
Continuous When the Collision Detection is set to Continuous, GameObjects with Rigidbody 2Ds and Collider 2Ds do not pass through each other during an update. Instead, Unity calculates the first impact point of any of the Collider 2Ds, and moves the GameObject there. Note that this takes more CPU time than Discrete.
Sleeping Mode Define how the GameObject “sleeps” to save processor time when it is at rest.
Never Sleep Sleeping is disabled (this should be avoided where possible, as it can impact system resources).
Start Awake Объект изначально активный (не спящий).
Start Asleep Объект изначально неактивный (спящий), но может быть активирован (разбужен) столкновениями.
Interpolate Define how the GameObject’s movement is interpolated between physics updates (useful when motion tends to be jerky).
None Никакое сглаживание движений не применяется.
Interpolate Movement is smoothed based on the GameObject’s positions in previous frames.
Extrapolate Движения сглаживается основываясь на предполагаемой позиции объекта в следующем кадре.
Constraints Define any restrictions on the Rigidbody 2D’s motion.
Freeze Position Stops the Rigidbody 2D moving in the world X & Y axes selectively.
Freeze Rotation Stops the Rigidbody 2D rotating around the Z axes selectively.

Body Type: Kinematic

A Kinematic Rigidbody 2D is designed to move under simulation, but only under very explicit user control. While a Dynamic Rigidbody 2D is affected by gravity and forces, a Kinematic Rigidbody 2D isn’t. For this reason, it is fast and has a lower demand on system resources than a Dynamic Rigidbody 2D. Kinematic Rigidbody 2D is designed to be repositioned explicitly via Rigidbody2D.MovePosition or Rigidbody2D.MoveRotation. Use physics queries to detect collisions, and scripts to decide where and how the Rigidbody 2D should move.

A Kinematic Rigidbody 2D does still move via its velocity, but the velocity is not affected by forces or gravity. A Kinematic Rigidbody 2D does not collide with other Kinematic Rigidbody 2Ds or with Static Rigidbody 2Ds; it only collides with Dynamic Rigidbody 2Ds. Similar to a Static Rigidbody 2D (see below), a Kinematic Rigidbody 2D behaves like an immovable object (as if it has infinite mass) during collisions. Mass-related properties are not available with this Body Type.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
TIP: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.
Use Full Kinematic Contacts Enable this setting (check the box) if you want the Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics engine when contacting another Rigidbody 2D component; instead it acts as an immovable object, with infinite mass. When Use Full Kinematic Contacts is disabled, the Kinematic Rigidbody 2D only collides with Dynamic Rigidbody 2Ds. See Rigidbody 2D properties: Use Full Kinematic Contacts, below, for more details. This box is unchecked by default.
Collision Detection Define how collisions between Collider 2D are detected.
Discrete When you set the Collision Detection to Discrete, GameObjects with Rigidbody 2Ds and Collider 2Ds can overlap or pass through each other during a physics update, if they are moving fast enough. Collision contacts are only generated at the new position.
Continuous When the Collision Detection is set to Continuous, GameObjects with Rigidbody 2Ds and Collider 2Ds do not pass through each other during an update. Instead, Unity calculates the first impact point of any of the Collider 2Ds, and moves the GameObject there. Note that this takes more CPU time than Discrete.
Sleeping Mode Define how the GameObject “sleeps” to save processor time when it is at rest.
Never Sleep Sleeping is disabled (this should be avoided where possible, as it can impact system resources).
Start Awake Объект изначально активный (не спящий).
Start Asleep Объект изначально неактивный (спящий), но может быть активирован (разбужен) столкновениями.
Interpolate Define how the GameObject’s movement is interpolated between physics updates (useful when motion tends to be jerky).
None Никакое сглаживание движений не применяется.
Interpolate Movement is smoothed based on the GameObject’s positions in previous frames.
Extrapolate Движения сглаживается основываясь на предполагаемой позиции объекта в следующем кадре.
Constraints Define any restrictions on the Rigidbody 2D’s motion.
Freeze Position Stops the Rigidbody 2D moving in the world’s x & y axes selectively.
Freeze Rotation Stops the Rigidbody 2D rotating around the world’s z axis selectively.

Body Type: Static

A Static Rigidbody 2D is designed to not move under simulation at all; if anything collides with it, a Static Rigidbody 2D behaves like an immovable object (as though it has infinite mass). It is also the least resource-intensive body type to use. A Static body only collides with Dynamic Rigidbody 2Ds. Having two Static Rigidbody 2Ds collide is not supported, since they are not designed to move.

Only a very limited set of properties are available for this Body Type.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
TIP: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.

There are two ways to mark a Rigidbody 2D as Static:

For the GameObject with the Collider 2D component not to have a Rigidbody 2D component at all. All such Collider 2Ds are internally considered to be attached to a single hidden Static Rigidbody 2D component.

For the GameObject to have a Rigidbody 2D and for that Rigidbody 2D to be set to Static.

Method 1 is a shorthand for making Static Collider 2Ds. When creating large numbers of Static Collider 2Ds, it is easier not to have to add a Rigidbody 2D for each GameObject with a Collider 2D.

Method 2 exists for performance reasons. If a Static Collider 2D needs to be moved or reconfigured at run time, it is faster to do so when it has its own Rigidbody 2D. If a group of Collider 2Ds needs to be moved or reconfigured at run time, it is faster to have them all be children of one parent Rigidbody 2D marked as Static than to move each GameObject individually.

Note: As stated above, Static Rigidbody 2Ds are designed not to move, and collisions between two Static Rigidbody 2D objects that intersect are not registered. However, Static Rigidbody 2Ds and Kinematic Rigidbody 2Ds will interact with each other if one of their Collider 2Ds is set to be a trigger. There is also a feature that changes what a Kinematic body will interact with (see Use Full Kinematic Contacts, below).

Rigidbody 2D properties

Simulated

Use the Simulated property to stop (unchecked) and start (checked) a Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds from interacting with the 2D physics simulation. Changing this property is much more memory and processor-efficient than enabling or disabling individual Collider 2D and Joint 2D components.

When the Simulated box is checked, the following occurs:

  • The Rigidbody 2D moves via the simulation (gravity and physics forces are applied)
  • Any attached Collider 2Ds continue creating new contacts and continuously re-evaluate contacts
  • Any attached Joint 2Ds are simulated and constrain the attached Rigidbody 2D
  • All internal physics objects for Rigidbody 2D, Collider 2D & Joint 2D stay in memory

When the Simulated box is unchecked, the following occurs:

  • The Rigidbody 2D is not moved by the simulation (gravity and physics forces are not applied)
  • The Rigidbody 2D does not create new contacts, and any attached Collider 2D contacts are destroyed
  • Any attached Joint 2Ds are not simulated, and do not constrain any attached Rigidbody 2Ds
  • All internal physics objects for Rigidbody 2D, Collider 2D and Joint 2D are left in memory
Why is unchecking Simulated more efficient than individual component controls?

In the 2D physics simulation, a Rigidbody 2D component controls the position and rotation of attached Collider 2D components, and allows Joint 2D components to use these positions and rotations as anchor points. A Collider 2D moves when the Rigidbody 2D it is attached to moves. The Collider 2D then calculates contacts with other Collider 2Ds attached to other Rigidbody 2Ds. Joint 2Ds also constrain Rigidbody 2D positions and rotations. All of this takes simulation time.

You can stop and start individual elements of the 2D physics simulation by enabling and disabling components individually. You can do this on both Collider 2D and Joint 2D components. However, enabling and disabling individual elements of the physics simulations has memory use and processor power costs. When elements of the simulation are disabled, the 2D physics engine doesn’t produce any internal physics-based objects to simulate. When elements of the simulation are enabled, the 2D physics engine does have internal physics-based objects to simulate. Enabling and disabling of 2D physics simulation components means internal GameObjects and physics-based components have to be created and destroyed; disabling the simulation is easier and more efficient than disabling individual components.

NOTE: When a Rigidbody 2D’s Simulated option is unchecked, any attached Collider 2D is effectively ‘invisible’, that is; it cannot be detected by any physics queries, such as Physics.Raycast.

Use Full Kinematic Contacts

Enable this setting (check the checkbox) if you want the Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics engine when contacting another Rigidbody 2D; it acts as an immovable object, with infinite mass.

When this setting is disabled (unchecked), a Kinematic Rigidbody 2D only collides with Dynamic Rigidbody 2Ds; it does not collide with other Kinematic Rigidbody 2Ds or Static Rigidbody 2Ds (note that trigger colliders are an exception to this rule). This means that no collision scripting callbacks (OnCollisionEnter, OnCollisionStay, OnCollisionExit) occur.

This can be inconvenient when you are using physics queries (such as Physics.Raycast) to detect where and how a Rigidbody 2D should move, and when you require multiple Kinematic Rigidbody 2Ds to interact with each other. Enable Use Full Kinematic Contacts to make Kinematic Rigidbody 2D components interact in this way.

Use Full Kinematic Contacts allows explicit position and rotation control of a Kinematic Rigidbody 2D, but still allows full collision callbacks. In a set-up where you need explicit control of all Rigidbody 2Ds, use Kinematic Rigidbody 2Ds in place of Dynamic Rigidbody 2Ds to still have full collision callback support.

Rigidbody 2D

A Rigidbody 2D component places an object under the control of the physics engine A system that simulates aspects of physical systems so that objects can accelerate correctly and be affected by collisions, gravity and other forces. More info
See in Glossary . Many concepts familiar from the standard Rigidbody A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary component carry over to Rigidbody 2D; the differences are that in 2D, objects can only move in the XY plane and can only rotate on an axis perpendicular to that plane.

The Rigidbody 2D component appears differently in the Unity Editor depending on which Body Type you have selected. See Body Type, below, to learn more.The Rigidbody 2D component appears differently in the Unity Editor depending on which Body Type you have selected. See Body Type, below, to learn more.

How a Rigidbody 2D works

Usually, the Unity Editor’s Transform component A Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform. More info
See in Glossary defines how a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary (and its child GameObjects) is positioned, rotated and scaled within the Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary . When it is changed, it updates other components, which may update things like where they render or where colliders An invisible shape that is used to handle physical collisions for an object. A collider doesn’t need to be exactly the same shape as the object’s mesh — a rough approximation is often more efficient and indistinguishable in gameplay. More info
See in Glossary are positioned. The 2D physics engine is able to move colliders and make them interact with each other, so a method is required for the physics engine to communicate this movement of colliders back to the Transform components. This movement and connection with colliders is what a Rigidbody 2D component is for.

The Rigidbody 2D component overrides the Transform and updates it to a position/rotation defined by the Rigidbody 2D. Note that while you can still override the Rigidbody 2D by modifying the Transform component yourself (because Unity exposes all properties on all components), doing so will cause problems such as GameObjects passing through or into each other, and unpredictable movement.

Any Collider 2D component added to the same GameObject or child GameObject is implicitly attached to that Rigidbody 2D. When a Collider 2D is attached to the Rigidbody 2D, it moves with it. A Collider 2D should never be moved directly using the Transform or any collider offset; the Rigidbody 2D should be moved instead. This offers the best performance and ensures correct collision A collision occurs when the physics engine detects that the colliders of two GameObjects make contact or overlap, when at least one has a Rigidbody component and is in motion. More info
See in Glossary detection. Collider 2Ds attached to the same Rigidbody 2D won’t collide with each other. This means you can create a set of colliders that act effectively as a single compound collider, all moving and rotating in sync with the Rigidbody 2D.

When designing a Scene, you are free to use a default Rigidbody 2D and start attaching colliders. These colliders allow any other colliders attached to different Rigidbody 2Ds to collide with each other.

Adding a Rigidbody 2D allows a sprite A 2D graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development. More info
See in Glossary to move in a physically convincing way by applying forces from the scripting API. When the appropriate collider component is also attached to the sprite GameObject, it is affected by collisions with other moving GameObjects. Using physics simplifies many common gameplay mechanics and allows for realistic behavior with minimal coding.

Body Type

The Rigidbody 2D component has a setting at the top labelled Body Type. The option you choose for this affects the other settings available on the component.

There are three options for Body Type; each defines a common and fixed behavior. Any Collider 2D attached to a Rigidbody 2D inherits the Rigidbody 2D’s Body Type. The three options are:

  • Dynamic
  • Kinematic
  • Static

The option you choose defines:

  • Movement (position & rotation) behavior
  • Collider interaction

Note that although Rigidbody 2Ds are often described as colliding with each other, it is the Collider 2Ds attached to each of those bodies which collide. Rigidbody 2Ds cannot collide with each other without colliders.

Changing the Body Type of a Rigidbody 2D can be a tricky process. When a Body Type changes, various mass-related internal properties are recalculated immediately, and all existing contacts for the Collider 2Ds attached to the Rigidbody 2D need to be re-evaluated during the GameObject’s next FixedUpdate. Depending on how many contacts and Collider 2Ds are attached to the body, changing the Body Type can cause variations in performance.

Body Type: Dynamic

A Dynamic Rigidbody 2D is designed to move under simulation. It has the full set of properties available to it such as finite mass and drag, and is affected by gravity and forces. A Dynamic body will collide with every other body type, and is the most interactive of body types. This is the default body type for a Rigidbody 2D, because it is the most common body type for things that need to move. It’s also the most performance-expensive body type, because of its dynamic nature and interactivity with everything around it. All Rigidbody 2D properties are available with this body type.

Do not use the Transform component to set the position or rotation of a Dynamic Rigidbody 2D. The simulation repositions a Dynamic Rigidbody 2D according to its velocity; you can change this directly via forces applied to it by scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary , or indirectly via collisions and gravity.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material An asset that defines how a surface should be rendered. More info
See in Glossary
Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
Tip: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint A physics component allowing a dynamic connection between Rigidbody components, usually allowing some degree of movement such as a hinge. More info
See in Glossary 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.
Use Auto Mass Check the box if you want the Rigidbody 2D to automatically detect the GameObject’s mass from its Collider 2D.
Mass Define the mass of the Rigidbody 2D. This is grayed out if you have selected Use Auto Mass.
Linear Drag Drag coefficient affecting positional movement.
Angular Drag Drag coefficient affecting rotational movement.
Gravity Scale Define the degree to which the GameObject is affected by gravity.
Collision Detection An automatic process performed by Unity which determines whether a moving GameObject with a Rigidbody and collider component has come into contact with any other colliders. More info
See in Glossary
Define how collisions between Collider 2D are detected.
Discrete When you set the Collision Detection to Discrete, GameObjects with Rigidbody 2Ds and Collider 2Ds can overlap or pass through each other during a physics update, if they are moving fast enough. Collision contacts are only generated at the new position.
Continuous When the Collision Detection is set to Continuous, GameObjects with Rigidbody 2Ds and Collider 2Ds do not pass through each other during an update. Instead, Unity calculates the first impact point of any of the Collider 2Ds, and moves the GameObject there. Note that this takes more CPU time than Discrete.
Sleeping Mode Define how the GameObject “sleeps” to save processor time when it is at rest.
Never Sleep Sleeping is disabled (this should be avoided where possible, as it can impact system resources).
Start Awake GameObject is initially awake.
Start Asleep GameObject is initially asleep but can be woken by collisions.
Interpolate The process of calculating values in-between two defined values. Used in animation (between keyframes), physics (between physics time-steps), and multiplayer (between network updates)
See in Glossary
Define how the GameObject’s movement is interpolated between physics updates (useful when motion tends to be jerky).
None No movement smoothing is applied.
Interpolate Movement is smoothed based on the GameObject’s positions in previous frames.
Extrapolate Movement is smoothed based on an estimate of its position in the next frame.
Constraints Settings on Joint components which limit movement or rotation. The type and number of constraints vary depending on the type of Joint. More info
See in Glossary
Define any restrictions on the Rigidbody 2D’s motion.
Freeze Position Stops the Rigidbody 2D moving in the world X & Y axes selectively.
Freeze Rotation Stops the Rigidbody 2D rotating around the Z axes selectively.

Body Type: Kinematic

A Kinematic Rigidbody 2D is designed to move under simulation, but only under very explicit user control. While a Dynamic Rigidbody 2D is affected by gravity and forces, a Kinematic Rigidbody 2D isn’t. For this reason, it is fast and has a lower demand on system resources than a Dynamic Rigidbody 2D. Kinematic Rigidbody 2D is designed to be repositioned explicitly via Rigidbody2D.MovePosition or Rigidbody2D.MoveRotation. Use physics queries to detect collisions, and scripts to decide where and how the Rigidbody 2D should move.

A Kinematic Rigidbody 2D does still move via its velocity, but the velocity is not affected by forces or gravity. A Kinematic Rigidbody 2D does not collide with other Kinematic Rigidbody 2Ds or with Static Rigidbody 2Ds; it only collides with Dynamic Rigidbody 2Ds. Similar to a Static Rigidbody 2D (see below), a Kinematic Rigidbody 2D behaves like an immovable object (as if it has infinite mass) during collisions. Mass-related properties are not available with this Body Type.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
TIP: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.
Use Full Kinematic Contacts Enable this setting (check the box) if you want the Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics engine when contacting another Rigidbody 2D component; instead it acts as an immovable object, with infinite mass. When Use Full Kinematic Contacts is disabled, the Kinematic Rigidbody 2D only collides with Dynamic Rigidbody 2Ds. See Rigidbody 2D properties: Use Full Kinematic Contacts, below, for more details. This box is unchecked by default.
Collision Detection Define how collisions between Collider 2D are detected.
Discrete When you set the Collision Detection to Discrete, GameObjects with Rigidbody 2Ds and Collider 2Ds can overlap or pass through each other during a physics update, if they are moving fast enough. Collision contacts are only generated at the new position.
Continuous When the Collision Detection is set to Continuous, GameObjects with Rigidbody 2Ds and Collider 2Ds do not pass through each other during an update. Instead, Unity calculates the first impact point of any of the Collider 2Ds, and moves the GameObject there. Note that this takes more CPU time than Discrete.
Sleeping Mode Define how the GameObject “sleeps” to save processor time when it is at rest.
Never Sleep Sleeping is disabled (this should be avoided where possible, as it can impact system resources).
Start Awake GameObject is initially awake.
Start Asleep GameObject is initially asleep but can be woken by collisions.
Interpolate Define how the GameObject’s movement is interpolated between physics updates (useful when motion tends to be jerky).
None No movement smoothing is applied.
Interpolate Movement is smoothed based on the GameObject’s positions in previous frames.
Extrapolate Movement is smoothed based on an estimate of its position in the next frame.
Constraints Define any restrictions on the Rigidbody 2D’s motion.
Freeze Position Stops the Rigidbody 2D moving in the world’s x & y axes selectively.
Freeze Rotation Stops the Rigidbody 2D rotating around the world’s z axis selectively.

Body Type: Static

A Static Rigidbody 2D is designed to not move under simulation at all; if anything collides with it, a Static Rigidbody 2D behaves like an immovable object (as though it has infinite mass). It is also the least resource-intensive body type to use. A Static body only collides with Dynamic Rigidbody 2Ds. Having two Static Rigidbody 2Ds collide is not supported, since they are not designed to move.

Only a very limited set of properties are available for this Body Type.

Property: Function:
Body Type Set the RigidBody 2D’s component settings, so that you can manipulate movement (position and rotation) behavior and Collider 2D interaction.
Options are: Dynamic, Kinematic, Static
Material Use this to specify a common material for all Collider 2Ds attached to a specific parent Rigidbody 2D.
Note: A Collider 2D uses its own Material property if it has one set. If there is no Material specified here or in the Collider 2D, the default option is None (Physics Material 2D). This uses a default Material which you can set in the Physics 2D window.
A Collider 2D uses the following order of priority to determine which Material setting to use:
1. A Physics Material 2D specified on the Collider 2D itself.
2. A Physics Material 2D specified on the attached Rigidbody 2D.
A Physics Material 2D default material specified in the Physics 2D window.
TIP: Use this to ensure that all Collider 2Ds attached to the same Static Body Type Rigidbody 2D can all use the same Material.
Simulated Enable Simulated (check the box) if you want the Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds to interact with the physics simulation during run time. If this is disabled (the box is unchecked), these components do not interact with the simulation. See Rigidbody 2D properties: Simulated, below, for more details. This box is checked by default.

There are two ways to mark a Rigidbody 2D as Static:

For the GameObject with the Collider 2D component not to have a Rigidbody 2D component at all. All such Collider 2Ds are internally considered to be attached to a single hidden Static Rigidbody 2D component.

For the GameObject to have a Rigidbody 2D and for that Rigidbody 2D to be set to Static.

Method 1 is a shorthand for making Static Collider 2Ds. When creating large numbers of Static Collider 2Ds, it is easier not to have to add a Rigidbody 2D for each GameObject with a Collider 2D.

Method 2 exists for performance reasons. If a Static Collider 2D needs to be moved or reconfigured at run time, it is faster to do so when it has its own Rigidbody 2D. If a group of Collider 2Ds needs to be moved or reconfigured at run time, it is faster to have them all be children of one parent Rigidbody 2D marked as Static than to move each GameObject individually.

Note: As stated above, Static Rigidbody 2Ds are designed not to move, and collisions between two Static Rigidbody 2D objects A 2D GameObject such as a tilemap or sprite. More info
See in Glossary that intersect are not registered. However, Static Rigidbody 2Ds and Kinematic Rigidbody 2Ds will interact with each other if one of their Collider 2Ds is set to be a trigger. There is also a feature that changes what a Kinematic body will interact with (see Use Full Kinematic Contacts, below).

Rigidbody 2D properties

Simulated

Use the Simulated property to stop (unchecked) and start (checked) a Rigidbody 2D and any attached Collider 2Ds and Joint 2Ds from interacting with the 2D physics simulation. Changing this property is much more memory and processor-efficient than enabling or disabling individual Collider 2D and Joint 2D components.

When the Simulated box is checked, the following occurs:

  • The Rigidbody 2D moves via the simulation (gravity and physics forces are applied)
  • Any attached Collider 2Ds continue creating new contacts and continuously re-evaluate contacts
  • Any attached Joint 2Ds are simulated and constrain the attached Rigidbody 2D
  • All internal physics objects for Rigidbody 2D, Collider 2D & Joint 2D stay in memory

When the Simulated box is unchecked, the following occurs:

  • The Rigidbody 2D is not moved by the simulation (gravity and physics forces are not applied)
  • The Rigidbody 2D does not create new contacts, and any attached Collider 2D contacts are destroyed
  • Any attached Joint 2Ds are not simulated, and do not constrain any attached Rigidbody 2Ds
  • All internal physics objects for Rigidbody 2D, Collider 2D and Joint 2D are left in memory
Why is unchecking Simulated more efficient than individual component controls?

In the 2D physics simulation, a Rigidbody 2D component controls the position and rotation of attached Collider 2D components, and allows Joint 2D components to use these positions and rotations as anchor points. A Collider 2D moves when the Rigidbody 2D it is attached to moves. The Collider 2D then calculates contacts with other Collider 2Ds attached to other Rigidbody 2Ds. Joint 2Ds also constrain Rigidbody 2D positions and rotations. All of this takes simulation time.

You can stop and start individual elements of the 2D physics simulation by enabling and disabling components individually. You can do this on both Collider 2D and Joint 2D components. However, enabling and disabling individual elements of the physics simulations has memory use and processor power costs. When elements of the simulation are disabled, the 2D physics engine doesn’t produce any internal physics-based objects to simulate. When elements of the simulation are enabled, the 2D physics engine does have internal physics-based objects to simulate. Enabling and disabling of 2D physics simulation components means internal GameObjects and physics-based components have to be created and destroyed; disabling the simulation is easier and more efficient than disabling individual components.

NOTE: When a Rigidbody 2D’s Simulated option is unchecked, any attached Collider 2D is effectively ‘invisible’, that is; it cannot be detected by any physics queries, such as Physics.Raycast.

Use Full Kinematic Contacts

Enable this setting (check the checkbox) if you want the Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics engine when contacting another Rigidbody 2D; it acts as an immovable object, with infinite mass.

When this setting is disabled (unchecked), a Kinematic Rigidbody 2D only collides with Dynamic Rigidbody 2Ds; it does not collide with other Kinematic Rigidbody 2Ds or Static Rigidbody 2Ds (note that trigger colliders are an exception to this rule). This means that no collision scripting callbacks (OnCollisionEnter, OnCollisionStay, OnCollisionExit) occur.

This can be inconvenient when you are using physics queries (such as Physics.Raycast) to detect where and how a Rigidbody 2D should move, and when you require multiple Kinematic Rigidbody 2Ds to interact with each other. Enable Use Full Kinematic Contacts to make Kinematic Rigidbody 2D components interact in this way.

Use Full Kinematic Contacts allows explicit position and rotation control of a Kinematic Rigidbody 2D, but still allows full collision callbacks. In a set-up where you need explicit control of all Rigidbody 2Ds, use Kinematic Rigidbody 2Ds in place of Dynamic Rigidbody 2Ds to still have full collision callback support.

Rigidbody 2D

Компонент Rigidbody 2D помещает объект под управление физического движка системы, которая имитирует аспекты физических систем, чтобы объекты могут правильно ускоряться и подвергаться воздействию столкновений, гравитации и других сил. Подробнее
См. в Словарь . Многие концепции знакомы из стандартного компонента Rigidbody , который позволяет GameObject, на который будет воздействовать смоделированная гравитация и другие силы. Подробнее
См. в Словарь перенос компонента в Rigidbody 2D; разница в том, что в 2D объекты могут двигаться только в плоскости XY и могут вращаться только вокруг оси, перпендикулярной этой плоскости.

Компонент Rigidbody 2D отображается в редакторе Unity по-разному в зависимости от выбранного типа тела.Компонент Rigidbody 2D отображается в редакторе Unity по-разному в зависимости от выбранного типа тела.. See Body Type

Как работает Rigidbody 2D

Обычно компонент Transform редактора Unity Компонент Transform определяет положение, поворот и масштаб каждого объекта в сцене. . Каждый GameObject имеет Transform. Подробнее
См. в Словарь определяет, как GameObject Фундаментальный объект в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в разделе Словарь (и его дочерние объекты GameObject) позиционируется , вращается и масштабируется внутри Сцена Сцена содержит окружение и меню вашей игры. Думайте о каждом уникальном файле сцены как об уникальном уровне. В каждой сцене вы размещаете свое окружение, препятствия и декорации, по сути проектируя и создавая свою игру по частям. Подробнее
См. в Словарь . Когда он изменяется, он обновляет другие компоненты, которые могут обновлять такие вещи, как то, где они отображаются или где коллайдеры используемая невидимая форма для обработки физических столкновений для объекта. Коллайдер не обязательно должен быть точно такой же формы, как сетка объекта — грубое приближение часто бывает более эффективным и неразличимым в игровом процессе. Подробнее
См. в Словарь . 2D-физический движок может перемещать коллайдеры и заставлять их взаимодействовать друг с другом, поэтому для физического движка требуется метод, чтобы передать это движение коллайдеров компонентам Transform. Это движение и связь с коллайдерами — то, для чего нужен 2D-компонент Rigidbody.

Компонент Rigidbody 2D переопределяет Transform и обновляет его до положения/поворота, заданного Rigidbody 2D. Обратите внимание, что, хотя вы по-прежнему можете переопределить Rigidbody 2D, изменив компонент Transform самостоятельно (поскольку Unity предоставляет все свойства для всех компонентов), это вызовет проблемы, такие как прохождение игровых объектов сквозь друг друга или друг друга, а также непредсказуемое движение.

Любой компонент Collider 2D, добавленный к тому же GameObject или дочернему GameObject, неявно присоединяется к этому Rigidbody 2D. Когда 2D-коллайдер прикреплен к 2D-твердому телу, он движется вместе с ним. 2D-коллайдер никогда не следует перемещать напрямую с помощью Transform или любого другого смещения коллайдера; Вместо этого следует перемещать Rigidbody 2D. Это обеспечивает наилучшую производительность и гарантирует правильное столкновение Столкновение происходит, когда физический движок обнаруживает, что коллайдеры двух игровых объектов соприкасаются или перекрываются. , когда хотя бы один имеет компонент Rigidbody и находится в движении. Подробнее
Смотреть в Словарь . 2D-коллайдеры, прикрепленные к одному и тому же 2D-объекту Rigidbody, не будут сталкиваться друг с другом. Это означает, что вы можете создать набор коллайдеров, которые эффективно действуют как единый составной коллайдер, движущийся и вращающийся синхронно с Rigidbody 2D.

При разработке сцены вы можете использовать 2D-объект Rigidbody по умолчанию и начать присоединять коллайдеры. Эти коллайдеры позволяют любым другим коллайдерам, прикрепленным к разным 2D-объектам Rigidbody, сталкиваться друг с другом.

Совет

Добавление Rigidbody 2D позволяет использовать спрайт двухмерные графические объекты. Если вы привыкли работать в 3D, спрайты — это, по сути, просто стандартные текстуры, но есть специальные приемы комбинирования текстур спрайтов и управления ими для повышения эффективности и удобства во время разработки. Подробнее
См. в Словарь , чтобы двигаться физически убедительно, применяя силы сценария. API. Когда соответствующий компонент коллайдера также присоединен к спрайту GameObject, на него влияют столкновения с другими движущимися объектами GameObject. Использование физики упрощает многие распространенные игровые механики и обеспечивает реалистичное поведение с минимальным кодированием.

Тип телосложения

У компонента Rigidbody 2D вверху есть настройка Тип тела. Выбранный вами вариант влияет на другие настройки, доступные в компоненте.

Существует три варианта типа телосложения; каждый определяет общее и фиксированное поведение. Любой 2D-коллайдер, прикрепленный к 2D-объекту Rigidbody, наследует Тип тела 2D-объекта Rigidbody. Три варианта:

  • Dynamic
  • Kinematic
  • Static

Выбранный вами вариант определяет:

  • Movement (position & rotation) behavior
  • Collider interaction

Обратите внимание, что, хотя 2D-объекты Rigidbody часто описываются как сталкивающиеся друг с другом, сталкиваются именно 2D-объекты Collider, прикрепленные к каждому из этих тел. 2D-объекты Rigidbody не могут сталкиваться друг с другом без коллайдеров.

Изменение типа тела Rigidbody 2D может быть сложным процессом. Когда тип тела изменяется, различные внутренние свойства, связанные с массой, немедленно пересчитываются, и все существующие контакты для 2D-коллайдера, прикрепленного к 2D-объекту Rigidbody, необходимо переоценить во время следующего FixedUpdate. В зависимости от того, сколько контактов и коллайдеров 2D прикреплено к телу, изменение типа тела может привести к изменению производительности.

Body Type: Dynamic

Dynamic Rigidbody 2D предназначен для перемещения при моделировании. Он обладает полным набором доступных ему свойств, таких как конечная масса и лобовое сопротивление, и на него влияют гравитация и силы. Динамическое тело будет сталкиваться с любым другим типом тела и является наиболее интерактивным из типов тела. Это тип тела по умолчанию для Rigidbody 2D, потому что это наиболее распространенный тип тела для вещей, которые должны двигаться. Это также наиболее затратный по производительности тип кузова из-за его динамичного характера и интерактивности со всем, что его окружает. Для этого типа тела доступны все свойства Rigidbody 2D.

Не используйте компонент Transform для установки положения или поворота Dynamic Rigidbody 2D. Моделирование изменяет положение Dynamic Rigidbody 2D в соответствии с его скоростью; вы можете изменить это напрямую с помощью сил, приложенных к нему с помощью скриптов фрагмент кода, который позволяет вам создавать свои собственные компоненты, запускать игру событий, изменяйте свойства компонентов с течением времени и реагируйте на ввод пользователя любым удобным для вас способом. Подробнее
См. в Словарь или косвенно через столкновения и гравитацию.

Свойства: Функции:
Body Type Установите параметры компонента RigidBody 2D, чтобы вы могли управлять поведением движения (положением и вращением) и взаимодействием 2D-коллайдера.
Варианты:Dynamic, Kinematic, Static
Material Ресурс, определяющий, как должна отображаться поверхность. More info
See in Словарь
Используйте это, чтобы указать общий материал для всех 2D-объектов Collider, прикрепленных к определенному родительскому 2D-объекту Rigidbody.
Примечание. Collider 2D использует собственное свойство материала, если оно установлено. Если здесь или в Collider 2D не указан Материал, по умолчанию используется параметр Нет (Physics Material 2D). При этом используется Материал по умолчанию, который можно установить в окне Physics 2D.
Collider 2D использует следующий порядок приоритета, чтобы определить, какой параметр Material использовать:
1. Физический материал 2D, указанный в самом коллайдере 2D.
2. Физический 2D-материал, указанный в прикрепленном 2D-объекте Rigidbody.
Материал Physics Material 2D по умолчанию, указанный в окне Physics 2D.
Совет: используйте это, чтобы убедиться, что все 2D-объекты Collider, прикрепленные к одному и тому же Static Body Type Rigidbody 2D, могут использовать один и тот же материал.
Simulated Включите Simulated (установите флажок), если вы хотите, чтобы Rigidbody 2D и любые прикрепленные Collider 2D и Joint Физический компонент, обеспечивающий динамическую связь между компонентами Rigidbody, обычно допускающий некоторую степень движения, например шарнир. Подробнее
См. в Словарь 2D для взаимодействия с физическим моделированием во время выполнения. Если это отключено (флажок снят), эти компоненты не взаимодействуют с симуляцией. Дополнительные сведения см. в разделе 2D-свойства Rigidbody: имитация ниже. Этот флажок установлен по умолчанию.
Use Auto Mass Установите флажок, если вы хотите, чтобы Rigidbody 2D автоматически определял массу GameObject по его 2D-коллайдеру.
Mass Задайте массу Rigidbody 2D. Это недоступно, если вы выбрали «Использовать автомассу».
Linear Drag Коэффициент сопротивления, влияющий на позиционное движение.
Angular Drag Коэффициент сопротивления, влияющий на вращательное движение.
Gravity Scale Определите степень воздействия гравитации на GameObject.
Обнаружение столкновений Автоматический процесс, выполняемый Unity, который определяет, вступал ли движущийся игровой объект с компонентом Rigidbody и коллайдера в контакт с какими-либо другими коллайдерами. Подробнее
См. в Словарь
Определить, как обнаруживаются столкновения между Collider 2D.
Discrete Когда для параметра Обнаружение столкновений задано значение Дискретное, игровые объекты с 2D-объектами Rigidbody и 2D-коллайдерами могут перекрываться или проходить сквозь друг друга во время обновления физики, если они движутся достаточно быстро. Контакты столкновения генерируются только в новой позиции.
Continuous Если для параметра Обнаружение столкновений установлено значение Непрерывно, игровые объекты с 2D-объектами Rigidbody и 2D-коллайдерами не проходят друг через друга во время обновления. Вместо этого Unity вычисляет первую точку столкновения любого из двухмерных объектов Collider и перемещает туда GameObject. Обратите внимание, что это требует больше процессорного времени, чем Discrete.
Sleeping Mode Определите, как GameObject «спит», чтобы сэкономить время процессора, когда он находится в состоянии покоя.
Never Sleep Спящий режим отключен (его следует по возможности избегать, так как это может повлиять на системные ресурсы).
Start Awake GameObject изначально бодрствует.
Start Asleep GameObject изначально спит, но может быть разбужен коллизиями.
Interpolate Процесс вычисления значений между двумя определенными значениями. Используется в анимации (между ключевыми кадрами), физике (между физическими временными шагами) и многопользовательской игре (между сетевыми обновлениями).
See in Словарь
Определите, как движение GameObject интерполируется между обновлениями физики (полезно, когда движение имеет тенденцию к рывкам).
None Сглаживание движения не применяется.
Interpolate Движение сглаживается на основе позиций GameObject в предыдущих кадрах..
Extrapolate Движение сглаживается на основе оценки его положения в следующем кадре.
Constraints Настройки компонентов соединения, которые ограничивают движение или вращение. Тип и количество ограничений зависит от типа соединения. More info
See in Словарь
Определите любые ограничения на движение Rigidbody 2D.
Freeze Position Выборочно останавливает перемещение Rigidbody 2D по мировым осям X и Y.
Freeze Rotation Выборочно останавливает вращение Rigidbody 2D вокруг оси Z.

Body Type: Kinematic

Кинематическое твердое тело 2D предназначено для перемещения в условиях моделирования, но только под очень явным контролем пользователя. В то время как на Dynamic Rigidbody 2D действуют гравитация и силы, на Kinematic Rigidbody 2D нет. По этой причине он быстрый и требует меньше системных ресурсов, чем Dynamic Rigidbody 2D. Кинематическая Rigidbody 2D предназначена для явного изменения положения с помощью Rigidbody2D.MovePosition или Rigidbody2D.MoveRotation. Используйте физические запросы для обнаружения столкновений и скрипты, чтобы решить, куда и как должно двигаться Rigidbody 2D.

Кинематическое твердое тело 2D по-прежнему движется за счет своей скорости, но на скорость не влияют силы или гравитация. Kinematic Rigidbody 2D не сталкивается с другими Kinematic Rigidbody 2D или Static Rigidbody 2D; он сталкивается только с Dynamic Rigidbody 2D. Подобно статическому твердому телу 2D (см. ниже), кинематическое жесткое тело 2D ведет себя как неподвижный объект (как если бы он имел бесконечную массу) во время столкновений. Свойства, связанные с массой, недоступны для этого типа телосложения.

Свойства: Функции:
Body Type Установите параметры компонента RigidBody 2D, чтобы вы могли управлять поведением движения (положением и вращением) и взаимодействием 2D-коллайдера.
Варианты: Dynamic, Kinematic, Static
Material Используйте это, чтобы указать общий материал для всех 2D-объектов Collider, прикрепленных к определенному родительскому 2D-объекту Rigidbody.
Примечание. Collider 2D использует собственное свойство материала, если оно установлено. Если здесь или в Collider 2D не указан Материал, по умолчанию используется параметр Нет (Physics Material 2D). При этом используется Материал по умолчанию, который можно установить в окне Physics 2D.
Collider 2D использует следующий порядок приоритета, чтобы определить, какой параметр Material использовать:
1. Физический материал 2D, указанный в самом коллайдере 2D.
2. Физический 2D-материал, указанный в прикрепленном 2D-объекте Rigidbody.
Материал Physics Material 2D по умолчанию, указанный в окне Physics 2D.
СОВЕТ. Используйте это, чтобы гарантировать, что все 2D-объекты Collider, прикрепленные к одному и тому же Static Body Type Rigidbody 2D, могут использовать один и тот же материал.
Simulated Включите Simulated (установите флажок), если вы хотите, чтобы Rigidbody 2D и любые присоединенные Collider 2D и Joint 2D взаимодействовали с физической симуляцией во время выполнения. Если это отключено (флажок снят), эти компоненты не взаимодействуют с симуляцией. Дополнительные сведения см. в разделе 2D-свойства Rigidbody: имитация ниже. Этот флажок установлен по умолчанию.
Use Full Kinematic Contacts Включите этот параметр (установите флажок), если хотите, чтобы кинематическое твердое 2D-тело сталкивалось со всеми типами 2D-тела Rigidbody. Это похоже на Dynamic Rigidbody 2D, за исключением того, что Kinematic Rigidbody 2D не перемещается физическим движком при контакте с другим компонентом Rigidbody 2D; вместо этого он действует как неподвижный объект с бесконечной массой. Если параметр Использовать полные кинематические контакты отключен, Кинематические 2D-объекты Rigidbody сталкиваются только с Динамическими 2D-объектами Rigidbody. Дополнительные сведения см. в разделе 2D-свойства Rigidbody: использование полных кинематических контактов ниже. Этот флажок не установлен по умолчанию.
Collision Detection Определите, как обнаруживаются столкновения между Collider 2D.
Discrete Когда для параметра Обнаружение столкновений задано значение Дискретное, игровые объекты с 2D-объектами Rigidbody и 2D-коллайдерами могут перекрываться или проходить сквозь друг друга во время обновления физики, если они движутся достаточно быстро. Контакты столкновения генерируются только в новой позиции.
Continuous Если для параметра Обнаружение столкновений установлено значение Непрерывно, игровые объекты с 2D-объектами Rigidbody и 2D-коллайдерами не проходят друг через друга во время обновления. Вместо этого Unity вычисляет первую точку столкновения любого из двухмерных объектов Collider и перемещает туда GameObject. Обратите внимание, что это требует больше процессорного времени, чем Discrete.
Sleeping Mode Определите, как GameObject «спит», чтобы сэкономить время процессора, когда он находится в состоянии покоя.
Never Sleep Спящий режим отключен (его следует по возможности избегать, так как это может повлиять на системные ресурсы).
Start Awake GameObject изначально бодрствует.
Start Asleep GameObject изначально спит, но может быть разбужен коллизиями.
Interpolate Определите, как движение GameObject интерполируется между обновлениями физики (полезно, когда движение имеет тенденцию к рывкам).
None Сглаживание движения не применяется.
Interpolate Движение сглаживается на основе позиций GameObject в предыдущих кадрах.
Extrapolate Движение сглаживается на основе оценки его положения в следующем кадре.
Constraints Определите любые ограничения на движение Rigidbody 2D.
Freeze Position Выборочно останавливает твердое тело 2D, перемещающееся по осям x и y в мире..
Freeze Rotation Выборочно останавливает вращение Rigidbody 2D вокруг мировой оси z.

Body Type: Static

Static Rigidbody 2D спроектирован таким образом, чтобы вообще не двигаться при моделировании; если с ним что-то сталкивается, статическое твердое тело 2D ведет себя как неподвижный объект (как если бы он имел бесконечную массу). Это также наименее ресурсоемкий тип кузова. Статическое тело сталкивается только с Динамическим твердым телом 2D. Столкновение двух Static Rigidbody 2D не поддерживается, поскольку они не предназначены для перемещения.

Для этого типа тела доступен только очень ограниченный набор свойств.

Свойства: Функции:
Body Type Установите параметры компонента RigidBody 2D, чтобы вы могли управлять поведением движения (положением и вращением) и взаимодействием 2D-коллайдера.
Варианты: Dynamic, Kinematic, Static
Material Используйте это, чтобы указать общий материал для всех 2D-объектов Collider, прикрепленных к определенному родительскому 2D-объекту Rigidbody.
Примечание. Collider 2D использует собственное свойство материала, если оно установлено. Если здесь или в Collider 2D не указан Материал, по умолчанию используется параметр Нет (Physics Material 2D). При этом используется Материал по умолчанию, который можно установить в окне Physics 2D.
Collider 2D использует следующий порядок приоритета, чтобы определить, какой параметр Material использовать:
1. Физический материал 2D, указанный в самом коллайдере 2D.
2. Физический 2D-материал, указанный в прикрепленном 2D-объекте Rigidbody.
Материал Physics Material 2D по умолчанию, указанный в окне Physics 2D.
СОВЕТ. Используйте это, чтобы гарантировать, что все 2D-объекты Collider, прикрепленные к одному и тому же Static Body Type Rigidbody 2D, могут использовать один и тот же материал.
Simulated Включите Simulated (установите флажок), если вы хотите, чтобы Rigidbody 2D и любые присоединенные Collider 2D и Joint 2D взаимодействовали с физической симуляцией во время выполнения. Если это отключено (флажок снят), эти компоненты не взаимодействуют с симуляцией. Дополнительные сведения см. в разделе 2D-свойства Rigidbody: имитация ниже. Этот флажок установлен по умолчанию.

Существует два способа пометить Rigidbody 2D как Static:

Чтобы GameObject с 2D-компонентом Collider вообще не имел 2D-компонента Rigidbody. Все такие 2D-объекты Collider внутренне считаются присоединенными к одному скрытому компоненту Static Rigidbody 2D.

Чтобы GameObject имел Rigidbody 2D и для этого Rigidbody 2D было задано значение Static.

Метод 1 — это сокращение для создания статических коллайдеров 2D. При создании большого количества Статических коллайдеров 2D проще не добавлять Rigidbody 2D для каждого игрового объекта с 2D-коллайдером.

Метод 2 существует из соображений производительности. Если во время выполнения Static Collider 2D нужно переместить или перенастроить, это можно сделать быстрее, если у него есть собственный Rigidbody 2D. Если группу 2D-объектов Collider необходимо переместить или изменить конфигурацию во время выполнения, быстрее сделать так, чтобы все они были дочерними элементами одного родительского 2D-объекта Rigidbody, помеченного как Static, чем перемещать каждый игровой объект по отдельности.

Примечание. Как указано выше, статические твердые 2D-объекты не допускают перемещения и столкновений между двумя статическими жесткими телами Двумерные объекты Двумерный игровой объект, например тайловая карта или спрайт. Подробнее
См. в Словарь , что пересечения не зарегистрированы. Однако Статические 2D-объекты Rigidbody и Кинематические 2D-объекты Rigidbody будут взаимодействовать друг с другом, если один из их 2D-коллайдеров установлен в качестве триггера. Существует также функция, которая изменяет то, с чем будет взаимодействовать кинематическое тело (см. раздел Использование полных кинематических контактов ниже).

2D-свойства жесткого тела

Имитация

Используйте свойство Simulated, чтобы остановить (снято) и запустить (с флажком) 2D-объект Rigidbody и любые присоединенные 2D-объекты Collider и 2D-объекты Joint от взаимодействия с 2D-моделированием физики. Изменение этого свойства намного эффективнее с точки зрения использования памяти и процессора, чем включение или отключение отдельных компонентов Collider 2D и Joint 2D.

Если установлен флажок Имитация, происходит следующее:

  • 2D-объект Rigidbody движется с помощью симуляции (применяются гравитационные и физические силы)
  • Все подключенные 2D-коллайдеры продолжают создавать новые контакты и постоянно переоценивать контакты
  • Любые присоединенные 2D-объекты Joint моделируются и ограничивают присоединенный 2D-объект Rigidbody.
  • Все внутренние физические объекты для Rigidbody 2D, Collider 2D и Joint 2D остаются в памяти

Если флажок Имитация не установлен, происходит следующее:

  • Твердое тело 2D не перемещается при моделировании (гравитация и физические силы не применяются)
  • 2D Rigidbody не создает новые контакты, а любые присоединенные контакты Collider 2D уничтожаются
  • Присоединенные 2D-объекты Joint не моделируются и не ограничивают присоединенные 2D-объекты Rigidbody.
  • Все внутренние физические объекты для Rigidbody 2D, Collider 2D и Joint 2D остаются в памяти
Почему снятие флажка «Имитация» более эффективно, чем управление отдельными компонентами?

В 2D-моделировании физики 2D-компонент Rigidbody управляет положением и вращением прикрепленных 2D-компонентов Collider и позволяет компонентам Joint 2D использовать эти положения и повороты в качестве опорных точек. Двухмерный коллайдер движется, когда твердое тело, к которому он прикреплен, движется. Затем Collider 2D рассчитывает контакты с другими Collider 2D, прикрепленными к другим 2D Rigidbody. Совместные 2D-объекты также ограничивают положения и повороты Rigidbody 2D. Все это требует времени моделирования.

Вы можете останавливать и запускать отдельные элементы 2D-моделирования физики, включая и отключая компоненты по отдельности. Вы можете сделать это как для компонентов Collider 2D, так и для компонентов Joint 2D. Однако включение и отключение отдельных элементов физического моделирования требует использования памяти и мощности процессора. Когда элементы моделирования отключены, 2D-физический движок не создает никаких внутренних физических объектов для моделирования. Когда элементы симуляции включены, 2D-физический движок имеет внутренние физические объекты для симуляции. Включение и отключение компонентов моделирования 2D-физики означает необходимость создания и уничтожения внутренних игровых объектов и компонентов, основанных на физике; отключить симуляцию проще и эффективнее, чем отключить отдельные компоненты.

ПРИМЕЧАНИЕ. Если флажок Имитация для Rigidbody 2D не установлен, любой прикрепленный 2D-коллайдер фактически «невидим», то есть; он не может быть обнаружен какими-либо физическими запросами, такими как Physics.Raycast.

Использовать полные кинематические контакты

Включите этот параметр (установите флажок), если вы хотите, чтобы кинематическое твердое 2D-тело сталкивалось со всеми типами твердого 2D-тела. Это похоже на Dynamic Rigidbody 2D, за исключением того, что Kinematic Rigidbody 2D не перемещается физическим движком при контакте с другим Rigidbody 2D; он действует как неподвижный объект с бесконечной массой.

Если этот параметр отключен (снят флажок), кинематическое твердое тело 2D сталкивается только с динамическим жестким телом 2D; он не сталкивается с другими Kinematic Rigidbody 2D или Static Rigidbody 2D (обратите внимание, что триггерные коллайдеры являются исключением из этого правила). Это означает, что никакие обратные вызовы сценариев коллизий (OnCollisionEnter, OnCollisionStay, OnCollisionExit).

Это может быть неудобно, если вы используете физические запросы (например, Physics.Raycast), чтобы определить, куда и как должен двигаться 2D-объект Rigidbody. и когда вам требуется несколько Kinematic Rigidbody 2D для взаимодействия друг с другом. Включите Использовать полные кинематические контакты, чтобы Кинематические компоненты Rigidbody 2D взаимодействовали таким образом.

Использовать полные кинематические контакты позволяет явно управлять положением и вращением кинематического твердого тела 2D, но по-прежнему допускает обратные вызовы полного столкновения. Если вам требуется явный контроль над всеми 2D-объектами Rigidbody, используйте Кинематические 2D-объекты Rigidbody вместо Динамические 2D-объекты Rigidbody, чтобы по-прежнему иметь полную поддержку обратного вызова столкновений.

Управление с клавиатуры и Rigidbody 2D

Привет! За базу возьму предыдущий урок, где мы написали скрипт, который центрировал книгу между двумя точками. Главной проблемой было то, что объект двигал я сам, да ещё и двигал через редактор, а не в режиме игры. Надо это исправить, и для этого мы используем сразу два решения: физика и управление с клавиатуры. В Unity есть компонент, которые называется Rigidbody. У него есть 2D версия, которую мы и будем использовать, т.к. она соответствует проекту/запросу.

Как нам подскажет документация Unity: Rigidbody (твёрдые тела) позволяют вашим игровым объектам взаимодействовать с помощью физики. Для реалистичного перемещения твёрдых тел, на последние воздействуют сила вращения и другие силы. Любой игровой объект должен содержать в себе твёрдое тело, чтобы быть подверженным гравитации, действовать согласно назначенным путём скриптинга силам, или взаимодействовать с другими объектами через физический движок NVIDIA PhysX.

Т.е. этот компонент делает объект физическим телом, на которое будут действовать различные силы (в т.ч. гравитация).

Но сам по себе Rigidbody не даёт представления о физических размерах объекта. Для этого существую различные коллайдеры:

Как понятно из названий, 2D версии подойдут 2D проектам, тогда как в 3D играх вы будете использовать объемные коллайдеры.

И от теории перейдём к практике.

Добавляем Rigidbody

Итак. Чтобы добавить физики выбранному объекту, нам нужно в инспекторе (при помощи Add Component) добавить Rigidbody 2D. Я хочу сделать физической точку Finish:

Новый компонент имеет такой вид:

Нам предложены поля для редактирования массы тела, выбор физического материала, сила (величина) гравитации, сопротивление при перемещении и т.д. Русская документация устарела, но английская в норме. Body Type может быть Dynamic (дефолтное), Kinematic или Static. В зависимости от выбранного типа следующие параметры могут отличаться. Но нас сейчас интересует именно Dynamic, который и предоставляет необходимую физику для тела.

Посмотрим, что из этого вышло?

Но куда интереснее будет сделать так, чтобы наша точка не падала в бездну. Добавим на сцену пустой спрайт. А в него: Box Collider 2D.

В Finish добавим Circle Collider 2D, который и определит размеры физического тела.

Box Collider 2D это буквально коробка коллайдер, который и поможет нам сделать препятствие для падающего диска. А Circle Collider это более сложный круглый коллайдер. Как вы понимаете, круглый коллайдер имеет несколько больше точек взаимодействия, так что по возможности лучше использовать более простые (тот же box).

Меняем размер платформы при помощи Transform, а заодно меняем и её местоположение, чтобы словить падающий диск. Коллайдер внутри должен автоматически соответствовать новому размеру.

Вот теперь всё работает отлично!

Можно ради интереса добавить других стеночек, да ещё и с разными углами наклона.

Физика работает, как и планировалось, теперь пора докинуть элементы правлены.

Немного о работе с Visual Studio

И отвлечемся для важного момента пользователей VS. Если мы просто открываем в студии скрипты, то их можно отредактировать и сохранить, но полноценным это использование назвать сложно. Например, подсказки будут минимальными и не будут касаться API Unity. Чтобы в полной мере насладиться написанием кода в IDE нам нужно открывать не скрипты отдельно, а создать VS проект. Сделать это можно прямо в Unity.

Должна открыться папка с файлом проекта .sln. Он то нам и нужен, запускаем и получаем свой проект с доступом к другим скриптам и подсказкам.

Кстати, новые скрипты могут быть не включены в проект, для этого нужно в Обозревателе решений отобразить все файлы и включить новые скрипты в проект:

Управляем движением объекта при помощи скрипта

Чтобы реализовать управление, нам нужно будет создать ещё один скрипт. Сделаем это. Пускай это будет какой-то UserControlScript. Управление физическим объектом может быть реализовано при помощи передаваемых направленных импульсов (Force) компоненту Rigidbody. Это можно делать при помощи векторов, умноженных на некоторую силу.

Но для начала нам нужно получить сам компонент Rigidbody 2D. Как вы уже знаете, можно создать публичную переменную, а уже в редакторе просто перетянуть на неё компонент (мы перетягивали объекты в прошлый раз, но с компонентами система та же).

Но такое решение мне не особо нравится. Так как и скрипт, и Rigidbody 2D находятся внутри одного объекта, а значит мы можем получить ссылку на объект Rigidbody при помощи функции GetComponent.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *