This page has been translated automatically.
Видеоуроки
Interface
Essentials
Advanced
Полезные советы
Программирование на C#
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Настройки и предпочтения
Работа с проектами
Настройка параметров узла
Setting Up Materials
Setting Up Properties
Освещение
Landscape Tool
Sandworm (Experimental)
Использование инструментов редактора для конкретных задач
Extending Editor Functionality
Встроенные объекты
Nodes
Objects
Effects
Decals
Light Sources
Geodetics
World Objects
Sound Objects
Pathfinding Objects
Players
Программирование
Основы
Настройка среды разработки
Примеры использования
UnigineScript
C++
C#
Унифицированный язык шейдеров UUSL
File Formats
Rebuilding the Engine Tools
GUI
Двойная точность координат
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Art Samples
Tutorials
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Физические тела

Bodies can be considered physical approximations of objects. They describe the object's behavior and represent a set of its physical parameters, such as mass, velocity, etc. It is the body that enables interaction of an object with other objects and external physical forces. Each type of body is used for simulation of a specific type of object: Тела (Body) можно считать физическим приближением объектов. Они описывают поведение объекта и представляют собой набор его физических параметров, таких как масса, скорость и т.д. Именно тело обеспечивает взаимодействие объекта с другими объектами и внешними физическими силами. Каждый тип тела используется для моделирования определенного типа объекта:

  • Rigid body (also requires a shape to be assigned) — enables simulation of objects in accordance with the rigid body dynamics. Rigid body (также требует назначения shape ) - позволяет моделировать объекты в соответствии с динамикой твердого тела .
  • Ragdoll body (also requires a shape to be assigned for each bone) — provides bone-animated characters with procedural animation of a death sequence. Ragdoll body (также требуется, чтобы для каждой кости был назначен shape ) - предоставляет персонажей с , анимацией на костях , с процедурной анимацией последовательности смерти.
  • Fracture body — enables real-time simulation of destructible objects. Fracture body - позволяет моделировать разрушаемые объекты в реальном времени.
  • Rope body — enables physical simulation of various types of ropes and wires. Rope body - позволяет физически моделировать различные типы веревок и проводов.
  • Cloth body — enables physical simulation of various types of cloth. Cloth body - позволяет физически моделировать различные типы ткани.
  • Water body — enables physical simulation of liquids of different density and viscous behavior including buoyancy effect and wave dynamics. Water body - позволяет физически моделировать жидкости различной плотности и вязкости, включая эффект плавучести и волновую динамику.

There are also two types of auxiliary bodies: Также есть два типа вспомогательных тел :

  • Dummy body — a static type of body without physical properties. It is used to attach other bodies via joints. Dummy body - статический тип тела без физических свойств. Оно используется для прикрепления других тел через сочленения (joints).
  • Path body — a static type of body without physical properties. It is a spline, along which an arbitrary rigid body can be moved. Path body - статический тип тела без физических свойств. Это путь, по которому можно перемещать произвольное твердое тело (rigid).

For quick visualization of all types of bodies, watch a fragment of our video tutorial on physics.Для быстрого ознакомления со всеми типами тел посмотрите фрагмент нашего видеоурока по физике .

Rigid Body DynamicsДинамика твердого тела#

Most physics simulations are based on rigid body dynamics. A rigid body is an ideal representation of a solid body, which occupies a finite volume of space. This volume of space is determined by a shape or a set of shapes assigned to the body. Rigid bodies cannot be deformed, i.e. their geometry does not change no matter what happens with this body. Rigid body dynamics is applied to the following bodies with shapes assigned:Большинство физических симуляций основано на динамике твердого тела . Тело Rigid - это идеальное представление твердого тела, занимающего конечный объем пространства. Этот объем пространства определяется формой или набором фигур, назначенных телу. Жесткие тела нельзя деформировать, т.е. их геометрия не меняется, что бы с этим телом ни происходило. Динамика твердого тела применяется к следующим телам с заданными формами (shapes):

After being enabled, all these bodies and their shapes that approximate the object's volume share common properties of rigid objects obeying Newtonian mechanics.После включения все эти тела и их формы, которые приблизительно соответствуют объему объекта, обладают общими свойствами твердых объектов, подчиняющихся механике Ньютона.

Run Lola Run

Ragdolls and rigid bodies moving according to the rigid body dynamicsРэгдоллы и твердые тела, движущиеся согласно динамике твердого тела

Watch a fragment of our video tutorial on physics for illustration of this article.Посмотрите фрагмент нашего видеоурока по физике , чтобы проиллюстрировать эту статью.

Basic ConceptsБазовые концепции#

A state of a rigid body at any moment is specified with its position, orientation in space (with respect to some reference point — center of mass), and velocity. There are two types of body motion and, therefore, two velocity components:Состояние твердого тела в любой момент времени задается его положением, ориентацией в пространстве (относительно некоторой опорной точки - центра масс) и скоростью . Есть два типа движения тела и, следовательно, две компоненты скорости:

  • Linear motion. If we imagine that the orientation of the body is fixed, then the only movement the body can undergo is translation motion — change in linear position. This change is performed with linear velocity. Линейное движение . Если мы представим, что ориентация тела фиксирована, то единственное движение, которое может совершить тело, - это поступательное движение - изменение линейного положения. Это изменение выполняется с линейной скоростью (Linear Velocity).
  • Angular motion. On the other hand, if we freeze the center of mass of our body in space, the only movement the body will be able to perform is rotation, which is described by angular velocity. Угловое движение . С другой стороны, если мы заморозим центр масс нашего тела в пространстве, единственное движение, которое сможет совершить тело, - это вращение, которое описывается угловой скоростью (Angular Velocity).
Примечание
Setting the body's linear or angular velocity will immediately make it move or rotate in a specified direction.Установка линейной или угловой скорости тела немедленно заставит его двигаться или вращаться в указанном направлении.

As the body moves, its linear and angular momenta change. The linear momentum can be thought of as an extent to which the body will continue to move along a straight path. It is the product of mass and linear velocity of the body: По мере движения тела его линейный и угловой моменты изменяются. Линейный импульс (Linear Impulse) можно представить как степень, до которой тело будет продолжать двигаться по прямому пути. Это произведение массы и линейной скорости тела:

p = m * v p = m * v

The body will keep on moving forever, unless affected by an external force or impulse. Force equals mass of the body multiplied by acceleration:Тело будет продолжать двигаться вечно, если на него не будет воздействовать внешняя сила или импульс. Сила (Force) равна массе тела, умноженной на ускорение:

F = m * a F = м * a

By causing the body to undergo acceleration (i.e., to change its velocity over time), force controls its velocity and position indirectly.Заставляя тело испытывать ускорение (то есть изменять его скорость с течением времени), сила косвенно управляет его скоростью и положением.

Примечание
Forces acting on a body do not affect it immediately — they are accumulated before each physics simulation frame, and during simulation the resulting force, if unbalanced, is applied. Then forces are reset to zero to be calculated anew for the next frame. The same is true for torques.Силы, действующие на тело, не влияют на него сразу - они накапливаются перед каждым фреймом моделирования физики , и во время моделирования применяется результирующая сила, если она не сбалансирована. Затем силы сбрасываются на ноль, чтобы рассчитать заново для следующего кадра. То же самое и с крутящим моментом.

Impulse is the integral of force over time. It may be regarded as a change in momentum of an object to which a resultant force is applied. For example, when two bodies collide, they exchange impulses that are equal and opposite, as Newton's third law applies, and result in moving apart. Импульс (Impulse) - это интеграл силы во времени. Это можно рассматривать как изменение количества движения объекта, к которому приложена равнодействующая сила. Например, когда два тела сталкиваются, они обмениваются импульсами, которые равны и противоположны, как применяется третий закон Ньютона, и в результате расходятся.

Similarly to the linear momentum, the angular momentum is the measure of the "quantity of rotation motion" and can be thought of as an extent to which the body will continue to rotate around an axis of symmetry. It is expressed as the product of the inertia tensor of the body and its angular velocity.Подобно линейному импульсу, угловой момент (Angular Momentum) является мерой «количества вращательного движения» и может рассматриваться как степень, до которой тело будет продолжать вращаться вокруг оси симметрии. Он выражается как произведение тензора инерции (Inertia tensor) тела и его угловой скорости.

Rotation continues until torque, a rotational force, is exerted on this body. Torque is the cross product of the radius vector (a vector from the center of mass to the point where torque is applied) and the force vector (the magnitude of the force). Loosely speaking, it acts like a lever affecting rotational speed.Вращение продолжается до тех пор, пока к этому телу не будет приложен крутящий момент (Torque) - сила вращения. Крутящий момент - это перекрестное произведение радиус-вектора (вектора от центра масс к точке приложения крутящего момента) и вектора силы (величина силы). Грубо говоря, он действует как рычаг, влияющий на скорость вращения.

Forces and impulses can also be applied to an arbitrary point of the body and may cause body rotation, when this point is not the center of mass. In this case, force is computed as a cross product of force vector and radius vector (from the center of mass to the necessary point) and is added to the torque. And the other way around, torque applied not to the center of mass increases force.Силы и импульсы также могут быть приложены к произвольной точке тела и могут вызывать вращение тела, когда эта точка не является центром масс. В этом случае сила вычисляется как произведение вектора силы и радиус-вектора (от центра масс до нужной точки) и добавляется к крутящему моменту. И наоборот, крутящий момент, приложенный не к центру масс, увеличивает силу.

Примечание
Unlike forces and torques, impulses immediately change body velocity as the physics is updated. В отличие от сил и моментов, импульсы немедленно изменяют скорость тела по мере обновления физики.

To sum it up, the movement is characterized by the following basic parameters:Таким образом, движение характеризуется следующими основными параметрами:

Линейное движение Угловое движение
Mass (scalar) Inertia tensor (mat3)
Linear velocity (vec3) Angular velocity (vec3)
Force(vec3)

Impulse ( vec3)
Torque (vec3)

Adjustable body parameters that determine its behavior in the framework of rigid body dynamics are as follows:Регулируемые параметры тела, определяющие его поведение в рамках динамики твердого тела, следующие:

MassМасса#

Mass of the object multiplied by gravity specified for the world defines its weight:

W = m * g
Масса объекта, умноженная на гравитацию , указанную для мира, определяет его вес:

W = m * g

The center of mass is automatically calculated as the mean location of mass of all shapes that approximate the object. It serves as a reference point for linear motion and rotation, as well as application of external force and torque. центр масс автоматически рассчитывается как среднее расположение масс всех форм, которые приблизительно соответствуют объекту. Он служит точкой отсчета для линейного движения и вращения, а также приложения внешней силы и крутящего момента.

Mass parameters of the body can be set up manually or determined automatically using the shape-based parameters. It is convenient when a body has several shapes.Массовые параметры тела можно настроить вручную или определить автоматически с помощью параметров shape-based . Это удобно, когда тело имеет несколько форм .

DensityПлотность#

Density of the objects is defined as its mass per unit volume:

ρ = m / V
Плотность объекта определяется как его масса на единицу объема: ρ = м / V

Density value evidently depends on the mass value and vice versa: the higher the values are, the heavier and more dense the object is.Очевидно, что значение плотности зависит от значения массы и наоборот: чем выше значения, тем тяжелее и плотнее объект.

Boxes of different mass and density

Buoyant boxes of different mass and densityПлавающие ящики разной массы и плотности

Density determines buoyancy of the body in accordance with Archimedes' principle. The higher the density, the less tendency a body has to float.Плотность определяет плавучесть тела по принципу Архимеда. Чем выше плотность, тем меньше у тела склонности к плаванию.

Linear Damping and Angular DampingЛинейное и угловое демпфирование#

When the object begins moving in a definite direction, the linear damping force slows it down to a complete stop. Similar to linear damping, angular damping reduces angular velocity of objects over time, so that their rotation ceases. To the linear damping of the body, the global Linear Damp is added, and the exponential function is calculated. In exactly the same way to angular damping of the body, the global Angular Damp is added.Когда объект начинает двигаться в определенном направлении, линейная демпфирующая сила (linear damping force) замедляет его до полной остановки. Подобно линейному демпфированию, угловое демпфирование (angular damping) снижает угловую скорость объектов с течением времени, так что их вращение прекращается. К линейному демпфированию тела добавляется глобальное Linear Damp и вычисляется экспоненциальная функция. Точно так же, как и угловое демпфирование тела, добавляется глобальное Angular Damp.

These two parameters ensure that objects smoothly come to a stop and no calculations are done for unnecessary motion.Эти два параметра обеспечивают плавную остановку объектов и отсутствие необходимости вычислять ненужное движение.

Maximum Linear Velocity and Maximum Angular VelocityМаксимальные линейная и угловая скорость#

Maximum linear and angular velocity define the maximum possible velocities of the body. Velocities that exceed this limit are clipped. For example, the maximum linear velocity parameter can help to avoid tunneling (penetration) effect. Максимальная линейная и угловая скорость определяют максимально возможные скорости тела. Скорости, превышающие этот предел, обрезаются. Например, параметр максимальной линейной скорости может помочь избежать эффекта туннелирования (проникновения).

Примечание
There are also global maximum linear and angular velocities thresholds. The global maximum is compared with the maximum set for the body, and the minimum value is chosen to clip the actual velocity.Также существуют пороги глобальных максимальных линейных и угловых скоростей. Глобальный максимум сравнивается с максимумом, установленным для тела, и выбирается минимальное значение для ограничения фактической скорости.

FrictionТрение#

Coefficient of friction allows to model more rough rubbing of surfaces and is opposite to the body's movement direction. The higher the value, the less tendency the body has to slide. The friction values of both surfaces being in contact are considered.Коэффициент трения (Friction) позволяет моделировать более грубое трение поверхностей и противоположен направлению движения тела. Чем выше значение, тем меньше тенденция к скольжению тела. Учитываются значения трения обеих соприкасающихся поверхностей.

The resulting calculated friction depends on the objects' masses and gravity, and the angle between contacting surfaces. For example, if a body slides down an inclined plane, the friction becomes lower because the force of gravity, which is perpendicular to the face of the surface, diminishes.Полученное вычисленное трение зависит от масс и силы тяжести объектов, а также угла между соприкасающимися поверхностями. Например, если тело скользит по наклонной плоскости, трение становится меньше, потому что уменьшается сила тяжести, перпендикулярная поверхности.

Friction is calculated at contact between physical bodies.Трение рассчитывается при контакте между физическими телами.

Примечание
If the Collision option is enabled for a surface, it also contributes to calculations.Если для поверхности включен параметр Collision, он также участвует в расчетах.

RestitutionВосстановление#

Coefficient of restitution determines the degree of relative kinetic energy retained after a collision. It defines how bouncy the object is by contacting with another object. It depends on the elasticity of materials of colliding bodies. The simulated restitution, like friction, considers the total value for both objects being in contact.Коэффициент восстановления (Restitution) определяет степень относительной кинетической энергии, сохраняющейся после столкновения. Он определяет степень упругости объекта при контакте с другим объектом. Это зависит от упругости материалов сталкивающихся тел. Смоделированная реституция, как и трение, учитывает общую стоимость обоих объектов, находящихся в контакте.

  • The maximum value of 1 models elastic collision. Objects bounce off according to the impulse they get by contact.Максимальное значение 1 моделирует упругое столкновение. Объекты отскакивают в соответствии с импульсом, который они получают при контакте.
  • The minimum value of 0 models inelastic collision. Objects do not bounce at all.Минимальное значение 0 моделирует неупругое столкновение. Объекты вообще не отскакивают.

Again, just like friction, restitution is calculated by the contact between physical bodies.Опять же, как и трение, возмещение рассчитывается путем контакта между физическими телами.

Примечание
If the Collision option is enabled for a surface, it also contributes to calculations.Если для поверхности включена опция Collision, она также способствует расчетам.

FreezingЗастывание (Freezing)#

When a body does not move and stays in the equilibrium for some time, it will most probably be immobile until an external force is exerted on it and urges it to move again. During this period of inactivity, there is actually no need to simulate it. This state is called freezing and it allows saving a great deal of computational resources.Когда тело не движется и какое-то время остается в равновесии, оно, скорее всего, будет неподвижным, пока на него не будет воздействовать внешняя сила, которая заставит его снова двигаться. Во время этого периода бездействия фактически нет необходимости моделировать его. Это состояние называется застыванием и позволяет сэкономить много вычислительных ресурсов.

Примечание
Freezing can be applied only to the following bodies: Застывание применимо только к телам:
Frozen boxes     Simulation starts again as the impulse unfreezes boxes
Замороженные синие и незамороженные красные коробки. Импульс, приложенный к пирамиде ящиков, разморозил все, кроме одного.

The body is frozen, i.e. stops to be simulated, if: Тело заморожено, т.е. перестает моделироваться, если:

  1. Its linear velocity is lower than Frozen linear velocity and its angular velocity is lower than Frozen angular velocity. Both velocity values must be lower at the same time, otherwise, the simulation will not stop.

    There are also Frozen linear velocity and Frozen angular velocity thresholds set for the whole world. These global freezing thresholds are compared to the ones set for each body, and the highest value is chosen to freeze the body.There are also Frozen linear velocity and Frozen angular velocity thresholds set for the whole world. These global freezing thresholds are compared to the ones set for each body, and the highest value is chosen to freeze the body.

    There are also Frozen linear velocity and Frozen angular velocity thresholds set for the whole world. These global freezing thresholds are compared to the ones set for each body, and the highest value is chosen to freeze the body.
    Его линейная скорость меньше Frozen linear velocity, а угловая скорость меньше Frozen angular velocity. Оба значения скорости должны быть ниже одновременно, иначе симуляция не остановится.

    There are also Frozen linear velocity and Frozen angular velocity thresholds set for the whole world. These global freezing thresholds are compared to the ones set for each body, and the highest value is chosen to freeze the body.Также для всего мира установлены пороги Frozen linear velocityиFrozen angular velocity. Эти глобальные пороги замораживания сравниваются с порогами, установленными для каждого тела, и выбирается максимальное значение, чтобы заморозить тело.

  2. Velocity values stay lower than frozen velocities for the number of Frozen frames. This is done to ensure that the body has really terminated its motion.Значения скорости остаются ниже фиксированных скоростей для числа Frozen frames. Это делается для того, чтобы тело действительно прекратило движение.

When the body is frozen, its linear and angular velocity are set to 0. The simulation of the body movement starts again as another non-frozen object touches it or some force is applied to it.Когда тело заморожено, его линейная и угловая скорость устанавливаются на 0 . Моделирование движения тела начинается снова, когда к нему прикасается другой незамерзший объект или к нему прикладывается некоторая сила.

Setting Body ParametersУстановка параметров тела#

The parameters of each body are determined by its type. To view or adjust these parameters via UnigineEditor:Параметры каждого кузова определяются его типом. Чтобы просмотреть или настроить эти параметры через UnigineEditor :

  1. Select a node in the Editor Viewport or in the World Nodes hierarchy window.Выберите узел в Editor Viewport или в окне иерархии World Nodes .
  2. Go to the Physics tab in the Parameters window.Перейдите на вкладку Physics в окне Parameters .
  3. Specify available body parameters.Укажите доступные параметры тела.
Последнее обновление: 24.11.2020
Build: ()