что такое rigidbody в unity

Rigidbody

Rigidbodies enable your GameObjects to act under the control of physics. The Rigidbody can receive forces and torque to make your objects move in a realistic way. Any GameObject must contain a Rigidbody to be influenced by gravity, act under added forces via scripting, or interact with other objects through the NVIDIA PhysX physics engine.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unity

Properties

Property:Function:
MassThe mass of the object (in kilograms by default).
DragHow much air resistance affects the object when moving from forces. 0 means no air resistance, and infinity makes the object stop moving immediately.
Angular DragHow much air resistance affects the object when rotating from torque. 0 means no air resistance. Note that you cannot make the object stop rotating just by setting its Angular Drag to infinity.
Use GravityIf enabled, the object is affected by gravity.
Is KinematicIf enabled, the object will not be driven by the physics engine, and can only be manipulated by its Transform. This is useful for moving platforms or if you want to animate a Rigidbody that has a HingeJoint attached.
InterpolateTry one of the options only if you are seeing jerkiness in your Rigidbody’s movement.
NoneNo Interpolation is applied.
InterpolateTransform is smoothed based on the Transform of the previous frame.
ExtrapolateTransform is smoothed based on the estimated Transform of the next frame.
Collision DetectionUsed to prevent fast moving objects from passing through other objects without detecting collisions.
DiscreteUse discrete collision detection against all other Colliders in the Scene. Other colliders will use discrete collision detection when testing for collision against it. Used for normal collisions (This is the default value).
ContinuousUse Discrete collision detection against dynamic Colliders (with a Rigidbody) and sweep-based continuous collision detection against static Colliders (without a Rigidbody). Rigidbodies set to Continuous Dynamic will use continuous collision detection when testing for collision against this rigidbody. Other rigidbodies will use Discrete Collision detection. Used for objects which the Continuous Dynamic detection needs to collide with. (This has a big impact on physics performance, leave it set to Discrete, if you don’t have issues with collisions of fast objects)
Continuous DynamicUse sweep-based continuous collision detection against GameOjects set to Continuous and Continuous Dynamic collision. It will also use continuous collision detection against static Colliders (without a Rigidbody). For all other colliders, it uses discrete collision detection. Used for fast moving objects.
Continuous SpeculativeUse speculative continuous collision detection against Rigidbodies and Colliders. This is also the only CCD mode that you can set kinematic bodies. This method tends to be less expensive than sweep-based continuous collision detection.
ConstraintsRestrictions on the Rigidbody’s motion:-
Freeze PositionStops the Rigidbody moving in the world X, Y and Z axes selectively.
Freeze RotationStops the Rigidbody rotating around the local X, Y and Z axes selectively.

Details

The biggest difference between manipulating the Transform versus the Rigidbody is the use of forces. Rigidbodies can receive forces and torque, but Transforms cannot. Transforms can be translated and rotated, but this is not the same as using physics. You’ll notice the distinct difference when you try it for yourself. Adding forces/torque to the Rigidbody will actually change the object’s position and rotation of the Transform component. This is why you should only be using one or the other. Changing the Transform while using physics could cause problems with collisions and other calculations.

Rigidbodies must be explicitly added to your GameObject before they will be affected by the physics engine. You can add a Rigidbody to your selected object from Components->Physics->Rigidbody in the menu. Now your object is physics-ready; it will fall under gravity and can receive forces via scripting, but you may need to add a Collider or a Joint to get it to behave exactly how you want.

Parenting

When an object is under physics control, it moves semi-independently of the way its transform parents move. If you move any parents, they will pull the Rigidbody child along with them. However, the Rigidbodies will still fall down due to gravity and react to collision events.

Scripting

To control your Rigidbodies, you will primarily use scripts to add forces or torque. You do this by calling AddForce() and AddTorque() on the object’s Rigidbody. Remember that you shouldn’t be directly altering the object’s Transform when you are using physics.

Animation

For some situations, mainly creating ragdoll effects, it is neccessary to switch control of the object between animations and physics. For this purpose Rigidbodies can be marked isKinematic. While the Rigidbody is marked isKinematic, it will not be affected by collisions, forces, or any other part of the physics system. This means that you will have to control the object by manipulating the Transform component directly. Kinematic Rigidbodies will affect other objects, but they themselves will not be affected by physics. For example, Joints which are attached to Kinematic objects will constrain any other Rigidbodies attached to them and Kinematic Rigidbodies will affect other Rigidbodies through collisions.

Colliders

Colliders are another kind of component that must be added alongside the Rigidbody in order to allow collisions to occur. If two Rigidbodies bump into each other, the physics engine will not calculate a collision unless both objects also have a Collider attached. Collider-less Rigidbodies will simply pass through each other during physics simulation.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unityColliders define the physical boundaries of a Rigidbody

Add a Collider with the Component->Physics menu. View the Component Reference page of any individual Collider for more specific information:

Compound Colliders

Compound Colliders are combinations of primitive Colliders, collectively acting as a single Rigidbody. They come in handy when you have a model that would be too complex or costly in terms of performance to simulate exactly, and want to simulate the collision of the shape in an optimal way using simple approximations. To create a Compound Collider, create child objects of your colliding object, then add a Collider component to each child object. This allows you to position, rotate, and scale each Collider easily and independently of one another. You can build your compound collider out of a number of primitive colliders and/or convex mesh colliders.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unityA real-world Compound Collider setup

In the above picture, the Gun Model GameObject has a Rigidbody attached, and multiple primitive Colliders as child GameObjects. When the Rigidbody parent is moved around by forces, the child Colliders move along with it. The primitive Colliders will collide with the environment’s Mesh Collider, and the parent Rigidbody will alter the way it moves based on forces being applied to it and how its child Colliders interact with other Colliders in the Scene.

Mesh Colliders can’t normally collide with each other. If a Mesh Collider is marked as Convex, then it can collide with another Mesh Collider. The typical solution is to use primitive Colliders for any objects that move, and Mesh Colliders for static background objects.

Note: Compound colliders return individual callbacks for each collider collision pair when using Collision Callbacks.

Continuous Collision Detection

Continuous collision detection is a feature to prevent fast-moving colliders from passing each other. This may happen when using normal (Discrete) collision detection, when an object is one side of a collider in one frame, and already passed the collider in the next frame. To solve this, you can enable continuous collision detection on the rigidbody of the fast-moving object. Set the collision detection mode to Continuous to prevent the rigidbody from passing through any static (ie, non-rigidbody) MeshColliders. Set it to Continuous Dynamic to also prevent the rigidbody from passing through any other supported rigidbodies with collision detection mode set to Continuous or Continuous Dynamic. Continuous collision detection is supported for Box-, Sphere- and CapsuleColliders. Note that continuous collision detection is intended as a safety net to catch collisions in cases where objects would otherwise pass through each other, but will not deliver physically accurate collision results, so you might still consider decreasing the fixed Time step value in the TimeManager inspector to make the simulation more precise, if you run into problems with fast moving objects.

Use the right size

If you are modeling a human make sure the model is around 2 meters tall in Unity. To check if your object has the right size compare it to the default cube. You can create a cube using GameObject > 3D Object > Cube. The cube’s height will be exactly 1 meter, so your human should be twice as tall.

If you aren’t able to adjust the mesh itself, you can change the uniform scale of a particular mesh asset by selecting it in Project View and choosing Assets->Import Settings… from the menu. Here, you can change the scale and re-import your mesh.

If your game requires that your GameObject needs to be instantiated at different scales, it is okay to adjust the values of your Transform’s scale axes. The downside is that the physics simulation must do more work at the time the object is instantiated, and could cause a performance drop in your game. This isn’t a terrible loss, but it is not as efficient as finalizing your scale with the other two options. Also keep in mind that non-uniform scales can create undesirable behaviors when Parenting is used. For these reasons it is always optimal to create your object at the correct scale in your modeling application.

Hints

2018–10–12 Page amended with editorial review

Continuous Speculative collision detection method added in 2018.3

Источник

Rigidbody (Твердое тело)

Rigidbodies enable your GameObjects to act under the control of physics. The Rigidbody can receive forces and torque to make your objects move in a realistic way. Any GameObject must contain a Rigidbody to be influenced by gravity, act under added forces via scripting, or interact with other objects through the NVIDIA PhysX physics engine.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unity

Свойства

Свойство:Функция:
MassThe mass of the object (in kilograms by default).
DragКакое воздушное сопротивление оказывается на объект пока он перемещается под воздействием этих сил. 0 означает отсутствие сопротивления, а бесконечность (infinity) тут же прекращает перемещение объекта.
Angular DragКакое воздушное сопротивление оказывается на объект пока он вращается под воздействием силы вращения. 0 означает отсутствие сопротивления. Учтите что вы не можете остановить вращение объекта путём установки его углового сопротивления (Angular Drag) в бесконечное (infinity) положение.
Use GravityПри включении на объект действует гравитация.
Is KinematicIf enabled, the object will not be driven by the physics engine, and can only be manipulated by its Transform. This is useful for moving platforms or if you want to animate a Rigidbody that has a HingeJoint attached.
InterpolateПопробуйте одну из опций если вы замечаете тряску в перемещении своего твёрдого тела.
NoneНе применено никакой интерполяции.
InterpolateСглаживание транформации основано на трансформации из предыдущего кадра.
ExtrapolateСглаживание трансформации основано на приблизительной трансформации следующего кадра.
Collision DetectionИспользуется для предотвращения проникновения быстро перемещающихся объектов сквозь другие объекты без определения столкновений.
DiscreteНа всех остальных коллайдерах сцены используйте осторожное (Discreet) обнаружение столкновений. Другие коллайдеры будут использовать осторожное обнаружение столкновений при проверке на столкновения против них. Используется для нормальных столкновений (стандартное значение).
ContinuousИспользуйте осторожное обнаружение столкновений против динамических коллайдеров (с твёрдыми телами) и непрерывное обнаружение столкновений против статичных меш коллайдеров (без твёрдых тел). Твёрдые тела установленные как непрерывные динамические (Continuous Dynamic) будут использовать непрерывное обнаружение столкновений при тестировании на столкновения против этого твёрдого тела. Другие твёрдые тела будут использовать осторожное обнаружение столкновений. Используется для объектов, с которыми нужно столкнуться при помощи динамического обнаружения столкновений. Всё это оказывает большое влияние на физическую производительность, поэтому оставьте данное значение установленным в Discrete, если не испытываете проблем со столкновением быстро движущихся объектов.
Continuous DynamicИспользуйте непрерывное обнаружение столкновений против объектов настроенных на непрерывное и непрерывное динамическое столкновение. Также будет использоваться непрерывное обнаружение столкновений против статичных меш коллайдеров (без твёрдых тел). Для всех остальных коллайдеров будет использоваться осторожное обнаружение столкновений. Используется для быстро движущихся объектов.
ConstraintsОграничения движения твёрдого тела:-
Freeze PositionВыборочно останавливает перемещение твёрдого тела по осям X, Y и Z.
Freeze RotationВыборочно останавливает вращение твёрдого тела по осям X, Y и Z.

Детали

Наибольшее отличие между управлением трансформациями и твёрдыми телами заключается в использовании сил. Твёрдые тела могут управляться силами и вращением, трансформации же не могут. Трансформации можно перемещать и вращать, но это не то же самое, что и использование физики. Вы заметите разницу, когда решите сами испробовать это на деле. Добавление силы/вращения к твёрдому телу позволит изменить позицию и вращение компонента трансформаций (Transform) объекта. Вот почему вам нужно использовать только один из них. Изменение трансформаций при использовании физики может создать проблемы столкновениях и других вычислениях.

Rigidbodies must be explicitly added to your GameObject before they will be affected by the physics engine. You can add a Rigidbody to your selected object from Components->Physics->Rigidbody in the menu. Now your object is physics-ready; it will fall under gravity and can receive forces via scripting, but you may need to add a Collider or a Joint to get it to behave exactly how you want.

Наследование

Когда объект находится под управлением физики, он перемещается частично независимо от своих родителей. Если вы переместите одного из родителей, они потянут за собой Rigidbody потомков. Однако, твёрдые тела также будут падать вниз под воздействием силы тяжести и реагировать на события столкновений.

Скриптинг

To control your Rigidbodies, you will primarily use scripts to add forces or torque. You do this by calling AddForce() and AddTorque() on the object’s Rigidbody. Remember that you shouldn’t be directly altering the object’s Transform when you are using physics.

Анимация

For some situations, mainly creating ragdoll effects, it is neccessary to switch control of the object between animations and physics. For this purpose Rigidbodies can be marked isKinematic. While the Rigidbody is marked isKinematic, it will not be affected by collisions, forces, or any other part of the physics system. This means that you will have to control the object by manipulating the Transform component directly. Kinematic Rigidbodies will affect other objects, but they themselves will not be affected by physics. For example, Joints which are attached to Kinematic objects will constrain any other Rigidbodies attached to them and Kinematic Rigidbodies will affect other Rigidbodies through collisions.

Коллайдеры

Коллайдеры это другой тип компонентов, которые должны быть добавлены наряду с твёрдыми телами, чтобы задействовать столкновения. Если два твёрдых тела врезаются друг в друга, физический движок не будет просчитывать столкновение, пока к обоим объектам не будет назначен коллайдер. Твёрдые тела не имеющие коллайдеров будут просто проходить сквозь друг друга при просчёте столкновений.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unityколлайдеры определяют физические границы твёрдого тела

Add a Collider with the Component->Physics menu. View the Component Reference page of any individual Collider for more specific information:

Составные коллайдеры

Compound Colliders are combinations of primitive Colliders, collectively acting as a single Collider. They come in handy when you have a model that would be too complex or costly in terms of performance to simulate exactly, and want to simulate the collision of the shape in an optimal way using simple approximations. To create a Compound Collider, create child objects of your colliding object, then add a Collider component to each child object. This allows you to position, rotate, and scale each Collider easily and independently of one another. You can build your compound collider out of a number of primitive colliders and/or convex mesh colliders.

что такое rigidbody в unity. Смотреть фото что такое rigidbody в unity. Смотреть картинку что такое rigidbody в unity. Картинка про что такое rigidbody в unity. Фото что такое rigidbody в unityНастройка составного коллайдера реального мира

На картинке сверху, игровой объект Gun Model с назначенным твёрдым телом и несколькими примитивными коллайдерами в качестве потомков игрового объекта. При движении Rigidbody родителя под воздействием сил, потомки коллайдеры будут двигаться вместе с ним в том же направлении. Примитивные коллайдеры будут сталкиваться с меш коллайдерами окружающей среды, и родительский Rigidbody изменит способ своего перемещения, основываясь на силах, применённых к нему и том, как его потомки коллайдеры взаимодействуют с другими коллайдерами в сцене.

Mesh Colliders can’t normally collide with each other. If a Mesh Collider is marked as Convex, then it can collide with another Mesh Collider. The typical solution is to use primitive Colliders for any objects that move, and Mesh Colliders for static background objects.

Непрерывное обнаружение столкновений

Continuous collision detection is a feature to prevent fast-moving colliders from passing each other. This may happen when using normal (Discrete) collision detection, when an object is one side of a collider in one frame, and already passed the collider in the next frame. To solve this, you can enable continuous collision detection on the rigidbody of the fast-moving object. Set the collision detection mode to Continuous to prevent the rigidbody from passing through any static (ie, non-rigidbody) MeshColliders. Set it to Continuous Dynamic to also prevent the rigidbody from passing through any other supported rigidbodies with collision detection mode set to Continuous or Continuous Dynamic. Непрерывное обнаружение столкновений поддерживается для Box-, Sphere- и Capsule коллайдеров. Учтите, что непрерывное обнаружение столкновений служит в качестве системы поддержки для отлова столкновений в тех случаях, когда объекты могли бы пройти сквозь друг друга, но она не предоставляет физически аккуратных результатов столкновений, поэтому вы можете всё ещё счесть нужным уменьшить значение фиксированного временного шага (fixed Time step) в инспекторе менеджера времени (TimeManager), чтобы симуляция прошла более точно если вы испытывали бы проблемы с быстро движущимися объектами.

Используйте правильный размер

If you are modeling a human make sure the model is around 2 meters tall in Unity. To check if your object has the right size compare it to the default cube. You can create a cube using GameObject > 3D Object > Cube. The cube’s height will be exactly 1 meter, so your human should be twice as tall.

If you aren’t able to adjust the mesh itself, you can change the uniform scale of a particular mesh asset by selecting it in Project View and choosing Assets->Import Settings… from the menu. Here, you can change the scale and re-import your mesh.

Если в вашей игре необходимо сделать так, чтобы создавались экземпляры объектов типа GameObject разного размера, будет вполне нормальным изменять значения масштаба осей трансформаций вашего объекта. Плохой стороной этого процесса является то, что физическая симуляция должна брать на себя основную часть работы во время создания экземпляров объекта, а это в свою очередь может сказаться на снижении производительности в вашей игре. Но это не ужасная потеря, и это не так уж эффективно как при использовании для масштабирования ваших объектов двух других опций. Также не забывайте о том, что неравномерное масштабирование может привести к непредсказуемому поведению при использовании наследования. Поэтому, в таких случаях лучше в своём пакете трёхмерного моделирования изначально создавать свои объекты в правильном масштабе.

Источник

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

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