Что такое коллайдер в юнити

от admin

Colliders

Collider components define the shape of a GameObject for the purposes of physical collisions. A collider, which is invisible, does not need to be the exact same shape as the GameObject’s mesh. A rough approximation of the mesh is often more efficient and indistinguishable in gameplay.

The simplest (and least processor-intensive) colliders are primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider. In 2D, you can use the Box Collider 2D and Circle Collider 2D. You can add any number of these to a single GameObject to create compound colliders.

Compound colliders

Compound colliders approximate the shape of a GameObject while keeping a low processor overhead. To get further flexibility, you can add additional colliders on child GameObjects. For instance, you can rotate boxes relative to the local axes of the parent GameObject. When you create a compound collider like this, you should only use one Rigidbody component, placed on the root GameObject in the hierarchy.

Primitive colliders do not work correctly with shear transforms. If you use a combination of rotations and non-uniform scales in the Transform hierarchy so that the resulting shape is no longer a primitive shape, the primitive collider cannot represent it correctly.

Mesh colliders

There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the GameObject’s mesh exactly. In 2D, the Polygon Collider 2D does not match the shape of the sprite graphic perfectly but you can refine the shape to any level of detail you like.

These colliders are much more processor-intensive than primitive types, so use them sparingly to maintain good performance. Also, a mesh collider cannot collide with another mesh collider (i.e., nothing happens when they make contact). You can get around this in some cases by marking the mesh collider as Convex in the Inspector. This generates the collider shape as a “convex hull” which is like the original mesh but with any undercuts filled in.

The benefit of this is that a convex mesh collider can collide with other mesh colliders so you can use this feature when you have a moving character with a suitable shape. However, a good rule is to use mesh colliders for scene geometry and approximate the shape of moving GameObjects using compound primitive colliders.

Static colliders

You can add colliders to a GameObject without a Rigidbody component to create floors, walls and other motionless elements of a Scene. These are referred to as static colliders. At the opposite, colliders on a GameObject that has a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don’t have a Rigidbody, they don’t move in response to collisions.

Physics materials

Когда коллайдеры взаимодействуют, их поверхностям надо симулировать свойства материала, из которого они теоретически должны состоять. Например, слой льда будет более скользким, в то время как резиновый мяч будет предлагать больше трения и будет очень упругим. Хотя форма коллайдеров и не деформируется во время коллизий, их трение и упругость можно настроить используя физические материалы (Physics Materials). Настроить параметры так, как хочется, можно методом проб и ошибок, но, например, материал льда будет иметь нулевое (или очень маленькое) трение, а резиновый материал будет с большим показателем трения и почти идеальной упругостью. Для дополнительной информации по доступным параметрам, читайте страницы справки Physic Material и Physics Material 2D. Учтите, что, по историческим причинам, 3D ассет называется Physic Material, в то время как 2D эквивалент называется Physics Material 2D (с “s” после “Physic”).

Triggers

В случае столкновения, система скриптинга может это обнаружить и выполнить действия, указанные в функции OnCollisionEnter . Однако вы также можете использовать физический движок просто для обнаружения того, что один коллайдер входит в пространство другого, без создания коллизии. Коллайдер, настроенный как триггер (с помощью свойства Is Trigger), не ведёт себя как твёрдый объект и просто будет пропускать другие коллайдеры сквозь себя. Когда другой коллайдер войдёт “на территорию” этого коллайдера, триггер вызовет функцию OnTriggerEnter в скриптах объекта, к которому присоединён триггер.

Collision callbacks for scripts

When collisions occur, the physics engine calls functions with specific names on any scripts attached to the objects involved. You can place any code you like in these functions to respond to the collision event. For example, you might play a crash sound effect when a car bumps into an obstacle.

On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter , OnTriggerStay and OnTriggerExit functions. Note that for 2D physics, there are equivalent functions with 2D appended to the name, eg, OnCollisionEnter2D . Full details of these functions and code samples can be found on the Script Reference page for the MonoBehaviour class.

With normal, non-trigger collisions, there is an additional detail that at least one of the objects involved must have a non-kinematic Rigidbody (ie, Is Kinematic must be switched off). If both objects are kinematic Rigidbodies then OnCollisionEnter , etc, will not be called. With trigger collisions, this restriction doesn’t apply and so both kinematic and non-kinematic Rigidbodies will prompt a call to OnTriggerEnter when they enter a trigger collider.

Collider interactions

Коллайдеры взаимодействуют друг с другом по разному, в зависимости от того, как настроены их компоненты Rigidbody. Тремя важными конфигурациями являются статичный коллайдер (Static Collider) (т.е. компонент Rigidbody отсутствует вообще), Rigidbody коллайдер (Rigidbody Collider), и кинематический Rigidbody коллайдер (Kinematic Rigidbody Collider).

Static Collider

A static collider is a GameObject that has a Collider but no Rigidbody. Static colliders are mostly used for level geometry which always stays at the same place and never moves around. Incoming Rigidbody objects collide with static colliders but don’t move them.

In particular cases, the physics engine optimizes for static colliders that never move. For instance, a vehicle resting on top of a static collider remains asleep even if you move this static collider. You can enable, disable, or move static colliders in runtime without specially affecting the physics engine computation speed. Also, you can safely scale a static Mesh Collider as long as the scale is uniform (not skewed).

Rigidbody Collider

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

Kinematic Rigidbody Collider

Это игровой объект, к которому прикреплён коллайдер и кинематический Rigidbody (т.е. свойство IsKinematic компонента Rigidbody включено). Изменяя компонент Transform, вы можете перемещать объект с кинематическим Rigidbody, но он не будет реагировать на коллизии и приложенные силы так же, как и не кинематические Rigidbody. Кинематические Rigidbody должны использоваться для коллайдеров, которые могут двигаться или периодически выключаться/включаться, иначе они будут вести себя как статичные коллайдеры. Примером этого является скользящая дверь, которая обычно является недвижимым физическим препятствием, но по надобности может открываться. В отличие от статичного коллайдера, движущийся кинематический Rigidbody будет применять трение к другим объектам и, в случае контакта, будет “будить” другие Rigidbody.

Даже когда они неподвижны, кинематические Rigidbody коллайдеры ведут себя иначе, в отличие от статичных коллайдеров. Например, если коллайдер настроен как триггер, то вам также понадобится добавить к нему Rigidbody, чтобы можно было в вашем скрипте принимать события триггера. Если вы не хотите, чтобы триггер падал под действием силы гравитации или подвергался влиянию физики, то тогда вы можете включить свойство IsKinematic.

A Rigidbody component can be switched between normal and kinematic behavior at any time using the IsKinematic property.

A common example of this is the “ragdoll” effect where a character normally moves under animation but is thrown physically by an explosion or a heavy collision. The character’s limbs can each be given their own Rigidbody component with IsKinematic enabled by default. The limbs will move normallly by animation until IsKinematic is switched off for all of them and they immediately behave as physics objects. At this point, a collision or explosion force will send the character flying with its limbs thrown in a convincing way.

Collision action matrix

Когда сталкиваются 2 объекта, количество различных событий в скрипте зависит от конфигураций компонентов Rigidbody столкнувшихся объектов. Схемы ниже содержат детали того, какие функции событий будут вызваны, основываясь на присоединённых к объектам компонентах. В некоторых комбинациях эффект производится только на один из двух объектов, так что помните правило — законы физики не применяются к объектам, у которых нет присоединённого Rigidbody.

Коллайдеры (Colliders)

Collider components define the shape of an object for the purposes of physical collisions. A collider, which is invisible, need not be the exact same shape as the object’s mesh and in fact, a rough approximation is often more efficient and indistinguishable in gameplay.

The simplest (and least processor-intensive) colliders are the so-called primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider. In 2D, you can use the Box Collider 2D and Circle Collider 2D. Any number of these can be added to a single object to create compound colliders.

With careful positioning and sizing, compound colliders can often approximate the shape of an object quite well while keeping a low processor overhead. Further flexibility can be gained by having additional colliders on child objects (eg, boxes can be rotated relative to the local axes of the parent object). When creating a compound collider like this, there should only be one Rigidbody component, placed on the root object in the hierarchy.

Note, that primitive colliders will not work correctly with shear transforms — that means that if you use a combination of rotations and non-uniform scales in the tranform hierarchy so that the resulting shape would no longer match a primitive shape, the primitive collider will not be able to represent it correctly.

There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the object’s mesh exactly. In 2D, the Polygon Collider 2D will generally not match the shape of the sprite graphic perfectly but you can refine the shape to any level of detail you like. These colliders are much more processor-intensive than primitive types, however, so use them sparingly to maintain good performance. Also, a mesh collider will normally be unable to collide with another mesh collider (ie, nothing will happen when they make contact). You can get around this in some cases by marking the mesh collider as Convex in the inspector. This will generate the collider shape as a “convex hull” which is like the original mesh but with any undercuts filled in. The benefit of this is that a convex mesh collider can collide with other mesh colliders so you may be able to use this feature when you have a moving character with a suitable shape. However, a good general rule is to use mesh colliders for scene geometry and approximate the shape of moving objects using compound primitive colliders.

Colliders can be added to an object without a Rigidbody component to create floors, walls and other motionless elements of a scene. These are referred to as static colliders. In general, you should not reposition static colliders by changing the Transform position since this will impact heavily on the performance of the physics engine. Colliders on an object that does have a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don’t have a Rigidbody, they will not move in response to collisions.

Страницы справки для различных типов коллайдеров, указанных выше, имеют дополнительную информацию об их свойствах и способах использования.

Физические материалы (Physics Materials)

When colliders interact, their surfaces need to simulate the properties of the material they are supposed to represent. For example, a sheet of ice will be slippery while a rubber ball will offer a lot of friction and be very bouncy. Although the shape of colliders is not deformed during collisions, their friction and bounce can be configured using Physics Materials. Getting the parameters just right can involve a bit of trial and error but an ice material, for example will have zero (or very low) friction and a rubber material with have high friction and near-perfect bounciness. See the reference pages for Physic Material and Physics Material 2D for further details on the available parameters. Note that for historical reasons, the 3D asset is actually called Physic Material (without the S) but the 2D equivalent is called Physics Material 2D (with the S).

Триггеры (Triggers)

The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger object’s scripts.

Функции обратного вызова при коллизии

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

On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter , OnTriggerStay and OnTriggerExit functions. Note that for 2D physics, there are equivalent functions with 2D appended to the name, eg, OnCollisionEnter2D . Full details of these functions and code samples can be found on the Script Reference page for the MonoBehaviour class.

У обычных не триггерных коллизий есть ещё дополнительная деталь: как минимум один из вовлечённых в коллизию объектов должен обладать не кинематическим Rigidbody (т.е. IsKinematic должен быть выключен). Если оба объекта являются кинематическими, то тогда не будут вызываться функции, вроде OnCollisionEnter и т.д. С триггерными столкновениями это условие не применяется, так что и кинематические и не кинематические Rigidbody будут незамедлительно вызывать OnTriggerEnter при пересечении триггерного коллайдера.

Взаимодействия коллайдеров

Коллайдеры взаимодействуют друг с другом по разному, в зависимости от того, как настроены их компоненты Rigidbody. Тремя важными конфигурациями являются статичный коллайдер (Static Collider) (т.е. компонент Rigidbody отсутствует вообще), Rigidbody коллайдер (Rigidbody Collider), и кинематический Rigidbody коллайдер (Kinematic Rigidbody Collider).

Статичный коллайдер (Static Collider)

Это игровой объект, у которого есть коллайдер, но нету Rigidbody. Статичные коллайдеры используются для геометрии уровней, которая всегда стоит на месте и совсем не двигается. Встречные Rigidbody объекты будут врезаться в статичный коллайдер, но его не сдвинут.

В физический движок заложено предположение, что статичные коллайдеры никогда не двигаются или меняются, и, на основе этого предположения, движок делает полезные оптимизации. Следовательно, статичные коллайдеры нельзя включать/выключать, двигать или масштабировать во время игрового процесса. Если вы измените статичный коллайдер, то в результате физическим движком будет вызван дополнительный внутренний перерасчёт, который будет сопровождаться большим падением производительности. Хуже того, изменения иногда могут оставить коллайдер в неопределённом состоянии, в результате чего будут производиться ошибочные физические расчёты. Например, рейкаст к изменённому статичному коллайдеру может не обнаружить коллайдера или обнаружить его в случайном месте в пространстве. Кроме того Rigidbody объекты, в которых врежется статичный коллайдер, не обязательно будут “разбужены”, и статичный коллайдер не применит никакого трения. По этим причинам, следует изменять только коллайдеры с Rigidbody. Если вы хотите, чтобы на коллайдер объекта не влияли встречные Rigidbody, но чтобы его можно было двигать при помощи скрипта, то вам следует прикрепить кинематический Rigidbody компонент к нему, нежели вообще не добавлять Rigidbody.

Rigidbody коллайдер (Rigidbody Collider)

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

Кинематические Rigidbody коллайдеры (Kinematic Rigidbody Collider)

Это игровой объект, к которому прикреплён коллайдер и кинематический Rigidbody (т.е. свойство IsKinematic компонента Rigidbody включено). Изменяя компонент Transform, вы можете перемещать объект с кинематическим Rigidbody, но он не будет реагировать на коллизии и приложенные силы так же, как и не кинематические Rigidbody. Кинематические Rigidbody должны использоваться для коллайдеров, которые могут двигаться или периодически выключаться/включаться, иначе они будут вести себя как статичные коллайдеры. Примером этого является скользящая дверь, которая обычно является недвижимым физическим препятствием, но по надобности может открываться. В отличие от статичного коллайдера, движущийся кинематический Rigidbody будет применять трение к другим объектам и, в случае контакта, будет “будить” другие Rigidbody.

Даже когда они неподвижны, кинематические Rigidbody коллайдеры ведут себя иначе, в отличие от статичных коллайдеров. Например, если коллайдер настроен как триггер, то вам также понадобится добавить к нему Rigidbody, чтобы можно было в вашем скрипте принимать события триггера. Если вы не хотите, чтобы триггер падал под действием силы гравитации или подвергался влиянию физики, то тогда вы можете включить свойство IsKinematic.

A Rigidbody component can be switched between normal and kinematic behavior at any time using the IsKinematic property.

A common example of this is the “ragdoll” effect where a character normally moves under animation but is thrown physically by an explosion or a heavy collision. The character’s limbs can each be given their own Rigidbody component with IsKinematic enabled by default. The limbs will move normallly by animation until IsKinematic is switched off for all of them and they immediately behave as physics objects. At this point, a collision or explosion force will send the character flying with its limbs thrown in a convincing way.

Матрица действий коллизии

Когда сталкиваются 2 объекта, количество различных событий в скрипте зависит от конфигураций компонентов Rigidbody столкнувшихся объектов. Схемы ниже содержат детали того, какие функции событий будут вызваны, основываясь на присоединённых к объектам компонентах. В некоторых комбинациях эффект производится только на один из двух объектов, так что помните правило — законы физики не применяются к объектам, у которых нет присоединённого Rigidbody.

Colliders

Компоненты коллайдера определяют форму GameObject основного объекта в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь для целей физического столкновения. Невидимый коллайдер не обязательно должен иметь ту же форму, что и сетка GameObject Основной графический примитив Unity. Меши составляют большую часть ваших 3D-миров. Unity поддерживает триангулированные или четырехугольные полигональные сетки. Поверхности Nurbs, Nurms, Subdiv должны быть преобразованы в полигоны. Подробнее
См. в Словарь . Грубая аппроксимация сетки часто более эффективна и неразличима в игровом процессе.

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

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

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

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

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

Однако в некоторых случаях даже составные коллайдеры недостаточно точны. В 3D вы можете использовать Mesh Collider компонент коллайдера произвольной формы, который принимает ссылку на сетку для определения формы поверхности столкновения. Подробнее
См. в Словарь , чтобы соответствовать форме сетки GameObject точно. В 2D 2D-полигональный коллайдер не соответствует форме спрайта Двухмерные графические объекты. Если вы привыкли работать в 3D, спрайты — это, по сути, просто стандартные текстуры, но есть специальные приемы комбинирования текстур спрайтов и управления ими для повышения эффективности и удобства во время разработки. Подробнее
смотрите в Словарь рисунок, но вы можете уточнить форму для любого уровня детализации метод Level Of Detail (LOD) — это оптимизация, треугольников, которые Unity должна отображать для GameObject, когда его расстояние от камеры увеличивается. Подробнее
Посмотрите в Словарь , который вам нравится.

Эти коллайдеры потребляют гораздо больше ресурсов процессора, чем примитивные типы, поэтому используйте их экономно, чтобы поддерживать хорошую производительность. Кроме того, меш-коллайдер не может столкнуться с другим меш-коллайдером (т. е. ничего не происходит, когда они вступают в контакт). В некоторых случаях это можно обойти, пометив коллайдер сетки как Выпуклый в Инспекторе A Unity. окно, в котором отображается информация о текущем выбранном игровом объекте, активе или настройках проекта, что позволяет просматривать и редактировать значения. Дополнительная информация
См. в Словарь . Это создает форму коллайдера в виде «выпуклой оболочки», которая похожа на исходную сетку, но с заполненными поднутрениями.

Преимущество этого заключается в том, что выпуклый коллайдер сетки может сталкиваться с другими коллайдерами сетки, поэтому вы можете использовать эту функцию, когда у вас есть движущийся персонаж с подходящей формой. Однако хорошим правилом является использование коллайдеров сетки для сцены Сцена содержит окружение и меню вашей игры. Думайте о каждом уникальном файле сцены как об уникальном уровне. В каждой сцене вы размещаете свое окружение, препятствия и декорации, по сути проектируя и создавая свою игру по частям. Подробнее
Просмотрите в Словарь геометрию и аппроксимируйте форму движущихся игровых объектов с помощью составных примитивных коллайдеров.

Статические коллайдеры

Вы можете добавлять коллайдеры в GameObject без компонента Rigidbody, чтобы создавать полы, стены и другие неподвижные элементы сцены. Они называются статическими коллайдерами. Напротив, коллайдеры на GameObject с Rigidbody называются динамическими коллайдерами. Статические коллайдеры могут взаимодействовать с динамическими коллайдерами, но, поскольку у них нет Rigidbody, они не двигаются в ответ на столкновения.

Материалы по физике

При взаимодействии коллайдеров их поверхности должны имитировать свойства материала, который они должны представлять. Например, лист льда будет скользким, в то время как резиновый мяч будет создавать сильное трение и будет очень упругим. Хотя форма коллайдеров не деформируется во время столкновений, их трение и отскок можно настроить с помощью Physics Materials. Получение правильных параметров может потребовать немного проб и ошибок. Скользкий материал, такой как лед, например, имеет нулевое (или очень низкое) трение. Такой цепкий материал, как резина, обладает высоким коэффициентом трения и почти идеальной упругостью. См. справочные страницы для Physic Material и PhysicsMaterial2D для получения дополнительной информации о доступных параметры. Обратите внимание, что по историческим причинам 3D-ресурс на самом деле называется Физический материал Физический ресурс для настройки эффектов трения и отскока сталкивающихся объектов. . Подробнее
См. в Словарь (без S), но 2D-эквивалент называется Physics Material 2D Используйте для регулировки трения и отскока, возникающего между 2D-физическими объектами, когда они сталкиваются Подробнее
См. в Словарь (с буквой S).

Триггеры

Система сценариев может определять возникновение коллизий и инициировать действия с помощью функции OnCollisionEnter . Однако вы также можете использовать physics engine Система, которая имитирует аспекты физических систем, чтобы объекты могли правильно ускоряться и подвергаться воздействию столкновений, гравитации и других сил. More info
See in Словарь просто обнаружить, когда один коллайдер входит в пространство другого, не создавая столкновения. Коллайдер, сконфигурированный как Триггер (используя свойство Is Trigger), не ведет себя как твердый объект и просто пропускает другие коллайдеры. Когда коллайдер входит в свое пространство, триггер вызывает функцию OnTriggerEnter для объекта триггера scripts Фрагмент кода, который позволяет вам создавать свои собственные Компоненты, запускать игровые события, изменять свойства Компонентов с течением времени и реагировать на ввод данных пользователем любым удобным для вас способом More info
See in Словарь .

Читать:
Как выложить приложение в microsoft store

Коллбэки для скриптов

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

При первом обновлении физики при обнаружении столкновения вызывается функция OnCollisionEnter . Во время обновлений, когда контакт поддерживается, вызывается OnCollisionStay и, наконец, OnCollisionExit указывает, что контакт был разорван. Триггерные коллайдеры вызывают аналогичные функции OnTriggerEnter , OnTriggerStay и OnTriggerExit . Обратите внимание, что для 2D-физики существуют эквивалентные функции с добавлением 2D к имени, например, OnCollisionEnter2D . Полную информацию об этих функциях и примеры кода можно найти на странице Справочник по сценариям для класса MonoBehaviour.

Для обычных столкновений без триггера есть дополнительная деталь: по крайней мере один из вовлеченных объектов должен иметь некинематическое Rigidbody (т. е. параметр Is Kinematic должен быть отключен). Если оба объекта являются кинематическими твердыми телами, то OnCollisionEnter и т. д. вызываться не будут. В случае столкновений триггеров это ограничение не применяется, поэтому как кинематические, так и некинематические твердые тела будут запрашивать вызов OnTriggerEnter при входе в коллайдер триггера.

Взаимодействие с коллайдером

Коллайдеры взаимодействуют друг с другом по-разному в зависимости от того, как настроены их компоненты твердого тела. Тремя важными конфигурациями являются Статический коллайдер (т. е. твердое тело вообще не подключено), Жесткий коллайдер и Кинематический твердотельный коллайдер.

Статический коллайдер

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

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

Жесткий коллайдер

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

Кинематический твердотельный коллайдер

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

Даже в неподвижном состоянии кинематические твердотельные коллайдеры ведут себя иначе, чем статические коллайдеры. Например, если коллайдер настроен как триггер, вам также необходимо добавить к нему твердое тело, чтобы получать события триггера в вашем скрипте. Если вы не хотите, чтобы триггер падал под действием силы тяжести или иным образом подвергался физическому воздействию, вы можете установить свойство IsKinematic для его твердого тела.

Компонент Rigidbody можно переключать между нормальным и кинематическим поведением в любое время с помощью свойства IsKinematic.

Распространенным примером этого является эффект «тряпичной куклы», когда персонаж обычно движется во время анимации, но физически отбрасывается взрывом или сильным столкновением. Каждой конечности персонажа может быть назначен отдельный компонент Rigidbody с включенным по умолчанию IsKinematic. Конечности двигаются в обычном режиме с помощью анимации, пока IsKinematic не будет отключена для всех из них, и они сразу же начнут вести себя как физические объекты. В этот момент сила столкновения или взрыва отправит персонажа в полет с отброшенными конечностями убедительным образом.

Матрица действий при столкновении

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

Что такое коллайдер в юнити

Включить компонент игрового объекта

Добавляем бокс-коллайдер (Box Collider)

Хитбокс игрока

Добавляем спрайт игрока

Магия Rigidbody
  1. Выберите объект Player в «Hierarchy».
  2. Добавьте компонент «Rigidbody 2D».

Настройки твердого тела игрока

  • Awake() вызывается один раз, когда объект создается. По сути аналог обычной функции-конструктора.
  • Start() выполняется после Awake() . Отличается тем, что метод Start() не вызывается, если скрипт не включен (remember the checkbox on a component in the «Inspector»).
  • Update() выполняется для каждого кадра in the main game loop.
  • FixedUpdate() вызывается каждый раз через определеннок число кадров. Вы можете вызывать этот метод вместо Update() когда имеете дело с физикой («RigidBody» и др.).
  • Destroy() вызывается, когда объект уничтожается. Это ваш последний шанс, чтобы очистить или выполнить код.
  • OnCollisionEnter2D(CollisionInfo2D info) выполняется, когда коллайдер объекта соприкасается с другим коллайдером.
  • OnCollisionExit2D(CollisionInfo2D info) выполняется, когда коллайдер объекта не соприкасается ни с одним другим коллайдером.
  • OnTriggerEnter2D(Collider2D otherCollider) выполняется, когда коллайдер объекта соприкасается с другим коллайдером с пометкой «Trigger».
  • OnTriggerExit2D(Collider2D otherCollider) выполняется, когда коллайдер объекта перестает соприкасаться с коллайдером, помеченным как «Trigger».
  1. Сначала определим публичную переменную, которая будет отображаться в окне «Инспектор». Это скорость, используемая для корабля.
  2. Сохраним движение для каждого кадра.
  3. Используем дефолтную ось, которую можно отредактировать в «Edit» -> «Project Settings» -> «Input». При этом мы получим целые значения между [-1, 1] , где 0 будет означать, что корабль неподвижен, 1 — движение вправо, -1 — влево.
  4. Умножим направление на скорость.
  5. Изменим скорость rigidbody. Это даст движку команду к перемещению объекта. Сделаем это в FixedUpdate() , предназначенном для всего, что связано с физикой.

Инспектор для сценария

Poulpi Sprite

  1. Скопируйте картинку в папку «Textures».
  2. Создайте новый спрайт, используя это изображение.
  3. Измените свойство «Масштаб» (Scale) в разделе Трансформирование (Transform) на (0.4, 0.4, 1) .
  4. Добавьте «Box Collider 2D» размером (4, 4) .
  5. Add a «Rigidbody 2D» with a «Gravity Scale» of 0 and «Fixed Angles» ticked.

Спрайт врага в Unity

Colliders

Collider components define the shape of an object for the purposes of physical collisions. A collider, which is invisible, need not be the exact same shape as the object’s mesh and in fact, a rough approximation is often more efficient and indistinguishable in gameplay.

The simplest (and least processor-intensive) colliders are the so-called primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider. In 2D, you can use the Box Collider 2D and Circle Collider 2D. Any number of these can be added to a single object to create compound colliders.

With careful positioning and sizing, compound colliders can often approximate the shape of an object quite well while keeping a low processor overhead. Further flexibility can be gained by having additional colliders on child objects (eg, boxes can be rotated relative to the local axes of the parent object). When creating a compound collider like this, there should only be one Rigidbody component, placed on the root object in the hierarchy.

Note, that primitive colliders will not work correctly with shear transforms — that means that if you use a combination of rotations and non-uniform scales in the tranform hierarchy so that the resulting shape would no longer match a primitive shape, the primitive collider will not be able to represent it correctly.

There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the object’s mesh exactly. In 2D, the Polygon Collider 2D will generally not match the shape of the sprite graphic perfectly but you can refine the shape to any level of detail you like. These colliders are much more processor-intensive than primitive types, however, so use them sparingly to maintain good performance. Also, a mesh collider will normally be unable to collide with another mesh collider (ie, nothing will happen when they make contact). You can get around this in some cases by marking the mesh collider as Convex in the inspector. This will generate the collider shape as a “convex hull” which is like the original mesh but with any undercuts filled in. The benefit of this is that a convex mesh collider can collide with other mesh colliders so you may be able to use this feature when you have a moving character with a suitable shape. However, a good general rule is to use mesh colliders for scene geometry and approximate the shape of moving objects using compound primitive colliders.

Colliders can be added to an object without a Rigidbody component to create floors, walls and other motionless elements of a scene. These are referred to as static colliders. In general, you should not reposition static colliders by changing the Transform position since this will impact heavily on the performance of the physics engine. Colliders on an object that does have a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don’t have a Rigidbody, they will not move in response to collisions.

The reference pages for the various collider types linked above have further information about their properties and uses.

Physics materials

When colliders interact, their surfaces need to simulate the properties of the material they are supposed to represent. For example, a sheet of ice will be slippery while a rubber ball will offer a lot of friction and be very bouncy. Although the shape of colliders is not deformed during collisions, their friction and bounce can be configured using Physics Materials. Getting the parameters just right can involve a bit of trial and error but an ice material, for example will have zero (or very low) friction and a rubber material with have high friction and near-perfect bounciness. See the reference pages for Physic Material and Physics Material 2D for further details on the available parameters. Note that for historical reasons, the 3D asset is actually called Physic Material (without the S) but the 2D equivalent is called Physics Material 2D (with the S).

Triggers

The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger object’s scripts.

Script actions taken on collision

When collisions occur, the physics engine calls functions with specific names on any scripts attached to the objects involved. You can place any code you like in these functions to respond to the collision event. For example, you might play a crash sound effect when a car bumps into an obstacle.

On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter , OnTriggerStay and OnTriggerExit functions. Note that for 2D physics, there are equivalent functions with 2D appended to the name, eg, OnCollisionEnter2D . Full details of these functions and code samples can be found on the Script Reference page for the MonoBehaviour class.

With normal, non-trigger collisions, there is an additional detail that at least one of the objects involved must have a non-kinematic Rigidbody (ie, Is Kinematic must be switched off). If both objects are kinematic Rigidbodies then OnCollisionEnter , etc, will not be called. With trigger collisions, this restriction doesn’t apply and so both kinematic and non-kinematic Rigidbodies will prompt a call to OnTriggerEnter when they enter a trigger collider.

Collider interactions

Colliders interact with each other differently depending on how their Rigidbody components are configured. The three important configurations are the Static Collider (ie, no Rigidbody is attached at all), the Rigidbody Collider and the Kinematic Rigidbody Collider.

Static Collider

This is a GameObject that has a Collider but no Rigidbody. Static colliders are used for level geometry which always stays at the same place and never moves around. Incoming rigidbody objects will collide with the static collider but will not move it.

The physics engine assumes that static colliders never move or change and can make useful optimizations based on this assumption. Consequently, static colliders should not be disabled/enabled, moved or scaled during gameplay. If you do change a static collider then this will result in extra internal recomputation by the physics engine which causes a major drop in performance. Worse still, the changes can sometimes leave the collider in an undefined state that produces erroneous physics calculations. For example a raycast against an altered Static Collider could fail to detect it, or detect it at a random position in space. Furthermore, Rigidbodies that are hit by a moving static collider will not necessarily be “awoken” and the static collider will not apply any friction. For these reasons, only colliders that are Rigidbodies should be altered. If you want a collider object that is not affected by incoming rigidbodies but can still be moved from a script then you should attach a Kinematic Rigidbody component to it rather than no Rigidbody at all.

Rigidbody Collider

This is a GameObject with a Collider and a normal, non-kinematic Rigidbody attached. Rigidbody colliders are fully simulated by the physics engine and can react to collisions and forces applied from a script. They can collide with other objects (including static colliders) and are the most commonly used Collider configuration in games that use physics.

Kinematic Rigidbody Collider

This is a GameObject with a Collider and a kinematic Rigidbody attached (ie, the IsKinematic property of the Rigidbody is enabled). You can move a kinematic rigidbody object from a script by modifying its Transform Component but it will not respond to collisions and forces like a non-kinematic rigidbody. Kinematic rigidbodies should be used for colliders that can be moved or disabled/enabled occasionally but that should otherwise behave like static colliders. An example of this is a sliding door that should normally act as an immovable physical obstacle but can be opened when necessary. Unlike a static collider, a moving kinematic rigidbody will apply friction to other objects and will “wake up” other rigidbodies when they make contact.

Even when immobile, kinematic rigidbody colliders have different behavior to static colliders. For example, if the collider is set to as a trigger then you also need to add a rigidbody to it in order to receive trigger events in your script. If you don’t want the trigger to fall under gravity or otherwise be affected by physics then you can set the IsKinematic property on its rigidbody.

A Rigidbody component can be switched between normal and kinematic behavior at any time using the IsKinematic property.

A common example of this is the “ragdoll” effect where a character normally moves under animation but is thrown physically by an explosion or a heavy collision. The character’s limbs can each be given their own Rigidbody component with IsKinematic enabled by default. The limbs will move normallly by animation until IsKinematic is switched off for all of them and they immediately behave as physics objects. At this point, a collision or explosion force will send the character flying with its limbs thrown in a convincing way.

Collision action matrix

When two objects collide, a number of different script events can occur depending on the configurations of the colliding objects’ rigidbodies. The charts below give details of which event functions are called based on the components that are attached to the objects. Some of the combinations only cause one of the two objects to be affected by the collision, but the general rule is that physics will not be applied to an object that doesn’t have a Rigidbody component attached.

Unity Collision: Super Simple Guide

Collision detection is required for all types of games. Detecting and utilizing the collision is implemented in a different manner in different game engines. In Unity, a collider can be added to any game object as a component. Also, you need to understand how colliders and Rigidbody work together to efficiently use them. Without a basic understanding of how Unity Colliders work, it will be very difficult to code the game mechanics. In this post, we will see how to use colliders in Unity and where to use OnCollisionEnter and OnTriggerEnter functions.

Introduction to Unity Colliders

Unity Collider in inspector

Unity Collider Types

Static collider

Static colliders are considered to be non-moving objects by Unity. Do not confuse static Gameobject with the static collider. If a Rigidbody is not attached to a collider then it’s a static collider. They do not move when an object Collides to with them. Though, they can be moved using transform, moving a static collider leads to performance loss during runtime.

Rigidbody collider

A Rigidbody collider works like a real-world object. It is governed by the forces of physics. If you apply force on it, it will move. In Unity, Rigidbody is used on an object which will move a lot during gameplay. Check the screenshot for how a Rigidbody is attached to a game object.

Kinematic Rigidbody collider

A kinematic Rigidbody is a Rigidbody that behaves like a static object. So, the next question is then why use a kinematic Rigidbody. The main reason to use a kinematic Rigidbody is to tell Unity that the object does not respond to forces but will be movable by script during runtime. The performance loss is very less in moving a kinematic Rigidbody compared to a Static object.

Non-trigger and Trigger collider

In Unity you can mark a collider as trigger using the check box in the inspector window. The behavior of the object changes if it is marked as a trigger.

Unity Colliders not marked as trigger

Unity will detect a collision only if one of the objects is a Rigidbody. That is, if you have two Gameobject marked as static colliders then collision between them will not be detected. It’s the same case with two kinematic Rigidbody. If you use the OnCollisionEnter function in any of the above cases, the function will not be called during a Collision. Find the collision matrix for unity colliders in the image below.

collision matrix for unity colliders

Unity collider marked as Trigger

When you mark a collider as a trigger, it no longer behaves like a solid object. It allows the other object to pass through it. But the time of one object entering another object’s space can trigger a function. With that, you can know if a collision has happened without actually creating a collision. You have to use the OnTriggerEnter function if the collider is Marked as a trigger. The collision matrix is a little different in the case of triggers.

Trigger collision matrix

Trigger collision doesn’t work in Unity if both the colliders are static colliders. In all the other cases the OnTriggerEnter is called. Knowing these basic things about colliders will help you set them up easily in your game.

If you did not understand the matrix completely then here is a simple comparison to help you. Consider static colliders as objects that don’t move like walls. Rigidbody collider denotes a moving object like a ball. Kinematic Rigidbody denotes that the object is not moved by physics but can be moved by script or animation.

Unity does not want to detect collision between two static objects so normal collision is detected only if one of the Gameobject is movable by physics. Whereas trigger function works a little differently. It works only if one of the colliders is marked as trigger and can be moved either by physics or script.

Detect Collision in Unity

  1. Create a new script. The new script contains Start and Update functions.
  2. Add the script to your player Gameobject.
  3. Add Rigidbody component to Player.
  4. Add collider to player and enemy Gameobjects.
  5. Add the function below to the new script. If your collider is a trigger then add OnTriggerEnter or else use OnCollisionEnter.
Unity OnCollisionEnter

Use this if your collider is not marked as trigger.

In this script we are using a normal collision. “col” returns the collider of the game object. We further check if the game object is an enemy. If yes, we destroy it. Remember either the parent Gameobject or the enemy game object needs to have a Rigidbody for this script to work.

Unity OnTriggerEnter

Use this if your collider is marked as trigger.

Pro tip: If the object is marked as trigger, it will pass through the obstacle and no collision physics will act.

Other features in Unity OnCollisionEnter and OnTriggerEnter

Both the examples of Unity OnCollisionEnter and OnTriggerEnter above show that you can get the Gameobject of the colliding object. Apart from that you can get a lot of data from the collision class object. Here is the list of things that you can get from the collision class

  1. collider- get the collider of the colliding object
  2. relative velocity- get the relative velocity between the colliding objects.
  3. transform- get the transform of the object hit.

Other Unity Collider functions

That summarizes the collider function in Unity. If you have any questions, you can post it in the comment box below.

There are few more functions to detect whether the Gameobject has exited the collision or its still colliding with another object.

Non-Trigger Collision
  • OnCollisionExit- Is called when the Collider exits a Collision.
  • OnCollisionStay – Is called when the Collider is still colliding with another object.
Trigger Collision
  • OnTriggerExit- Is called when the Trigger Collider exits a Collision.
  • OnTriggerStay- Is called when the Trigger Collider is still colliding with another object.

Unity Collision in 3D vs 2D

Collision in 2D is very similar to 3D. You have to add the word 2D in all the functions and colliders. Here is a comparison table to understand the same. Also, while adding the collider to a 2D object, you need to add a 2D collider. This is a very common mistake made by a lot of Unity users.

3D collider 2D Collider
OnCollisionEnter OnCollisionEnter2D
OnTriggerEnter OnTriggerEnter2D
OnCollisionExit OnCollisionExit2D
OnTriggerExit OnTriggerExit2D
OnCollisionStay OnCollisionStay2D
OnTriggerStay OnTriggerStay2D
Collider Collider2D
Collision Collision2D
Rigidbody Rigidbody2D
BoxCollider BoxCollider2D
MeshCollider PolygonCollider2D
SphereCollider CircleCollider
CapsuleCollider CapsuleCollider2D
TerrainCollider EdgeCollider2D or TilemapCollider2D
WheelCollider CircleCollider2D

If you have any other questions regarding Unity collider then leave them in the comment box below.

Похожие статьи