Погружение в скрипты игрового движка Unity3d, ч.1
Игровой объект
Создание нового игрового объекта с именем MyObject.
Созданный объект будет доступен по ссылку myObject.
Поиск объекта по его имени.
Теги можно использовать для помечания группы объектов со сходными свойствами, либо использующиеся в единой сцене.
Поиск объекта по тегу, возвращает единственный объект:
Возвращает список всех объектов с указанным тегом:
Проверка на наличие у объекта требуемого тега. Возвращает true, если у указанного объекта имеется тег MyTag:
Уничтожение объекта через минуту, после его создания:
Возвращает компонент component, привязанный к объекту GameObject, либо null, если объект не содержит данного компонента. Может использоваться, например, для доступа к другим скриптам, привязанным к объекту.
Возвращает все имеющиеся у объекта компоненты типа componentType.
Привязать компонент myComponent к объекту GameObject и получить ссылку на него.
Положение игрового объекта
Свойство transform объекта GameObject содержит в себе данные о положении объекта в игровом мире.
Возвращает глобальные координаты объекта в игровом мире. Возвращаемая величина имеет тип Vector3, который представляет из себя список из 3 координат — x, y и z:
Переместить объект в точку 0, 10, 0 игрового мира.
Тоже самое, что и в случае глобальных координат, но с локальными. Локальные координаты расситываются относительно родительского объекта. В случае отсутствия родительского объекта локальные координаты совпадают с глобальными:
Поворот объекта в углах Эйлера. Метод также возвращает координаты в виде объекта Vector3:
Тоже самое, что и предыдущий пример, но поворот объекта рассчитывается относительно родительского объекта:
Текущий угол поворота объекта, основанный на кватернионах. Возвращает объект типа Quaternion.
Текущий поворот объекта, основанный на кватернионах, но относительно родительского объекта:
Сброс угла поворота объекта:
Вращаем наш объект в указанную сторону со скоростью 1 градус в секунду. Принимает в качестве координат объект типа Vector3. Метод deltaTime объекта Time содержит время в секундах, затраченное на выполнение предыдущего кадра:
Тоже самое, что и предыдущий пример, но вращение объекта относительно координат родителя:
Перемещаем наш объект в указанном направлении со скоростью 1 юнит в секунду. Также принимает в качестве координат объект класса Vector3:
Физические свойства игрового объекта
Метод rigidbody объекта GameObject хранит в себе его физические свойства. Прежде, чем использовать метод rigidbody, его необходимо добавить к игровому объекту.
Получаем/задаем вектор скорости объекта:
Сила противодействия объекта. Может использоваться для замедления скорости, в среде с отсутствующей силой трения. Наиболее часто используется для замедления падающих объектов, например при создании парашюта. Принимает в качестве параметра целое число:
Задание массы объекту. Рекомендуется использовать массу в пределах от 0.1 до 10. Использование слишком больших значений может привести к непредсказуемым результатам при расчете физики:
Влияние на объект гравитации. Принимает в качестве параметра булево значение. Позволяет отключить влияние гравитации на отдельные объекты:
Влияние физики на игровой объект. Позволяет отключить частично, либо полностью влияние физических законов на объект:
Запрет на вращение объекта. Наиболее часто используется, когда необходимо сохранить определенный угол поворота даже после столкновения с другими объектами:
Указание координат точки центра массы объекта. Применяет координаты в виде уже знакомого нам объекта Vector3.
Использовать ли для объекта обнаружение столкновений с другими объектами. Можно выключить, тогда ваш объект будет игнорировать любые столкновения:
Режим определения столкновений между объектами. Можно указать несколько разных режимов:
CollisionDetectionMode.ContinuousDynamic для быстро движущихся объектов;
CollisionDetectionMode.Continuous для столкновений с быстро движущимися объектами;
CollisionDetectionMode.Discrete (по умолчанию) для обычных столкновений;
В случае отсутствия проблем с определением столкновений рекомендуется использовать свойство по умолчанию.
Задать плотность объекта:
Применить импульс к объекту с указанным вектором. В результате применения импульса объект придет в движение пропорционально силе импульса.
Применить импульс к объекту с вектором в его (объекта) системы координат:
Добавить объекту крутящий момент. Применение данного метода заставит объект вращаться вокруг своего центра масс GameObject.rigidbody.centerOfMass.
Тоже самое, что и предыдущий пример, но относительно координат объекта:
Применение импульса к объекту из внешней указанной точки. Заставляет объект двигаться и вращаться одновременно. Может использоваться, например, для симуляции попадания в объект пули. Первый параметр указывает вектор направления силы, второй параметр — исходную точку направления силы.
Для полноценной симуляции объемных взрывов в Unity3D есть отдельный метод. Первый параметр метода позволяет указать мощность импульса, второй параметр — точку, из которой исходит импульс, третий параметр — радиус распространения импульса, четвертый параметр — модификатор сжатия сферы распространения силы, пятый, необязательный, параметр указывает тип используемого импульса:
Заставить объект «уснуть», и запретить дальнейший расчет физических показателей для него:
Проверить «заснул» ли объект:
«Разбудить» объект для возможности дальнейшего применения влияния физики на него:
Трассировка лучей
Один из самых часто используемых в разработке на Unity3D объект, это Ray. Данный объект позволяет выпустить луч из указанной точки, в указанном направлении, и вернуть некоторые свойства объектов, которых он смог достичь.
Создаем объект класса RaycastHit, который содержит информацию об объекте, с которым столкнулся луч:
Отправляем луч длиной в 50 юнитов из позиции rayPosition в направлении rayVector, и заносим объект, с которым столкнулся луч в переменную hit:
Получаем дистанцию до объекта, с которым столкнулся луч. Дистанция не может быть больше, чем протяженность луча:
Иногда бывает необходимо получить имя объекта, с которым произошло столкновение луча. Наиболее простой способ это сделать:
Для получения тега объекта используем следующий способ:
Unity3D содержит еще множество различных методов и объектов, полезных и не очень. К сожалению полный их обзор увеличил бы и без того объемную статью, поэтому я постараюсь рассказать об остальном более подробно в будущем, если мне представится такая возможность. Я бы хотел пожелать опытным разработчикам побольше интересных проектов, а начинающим — успехов и интересных открытий. Спасибо, что уделили внимание данной статье.
Rigidbody 2D

How a Rigidbody 2D works
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:
The option you choose defines:
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.
| 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:
When the Simulated box is unchecked, the following occurs:
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.







