Capsule Collider
Capsule Collider состоит из двух полусфер, соединённых между собой цилиндром. Это такая же форма, как и у примитива капсула(Capsule).

Свойства
| Свойство: | Функция: |
|---|---|
| Is Trigger | Если включено, этот Коллайдер используется для запуска событий, и игнорируется физическим движком. |
| Material | Ссылка на физический материал, который определит, как этот коллайдер должен взаимодействовать с другими. |
| Center | Позиция коллайдера в локальном пространстве объекта. |
| Radius | Радиус ширины коллайдера в локальном пространстве. |
| Height | Общая высота коллайдера. |
| Direction | Ось, вдоль которой расположен коллайдер в локальном пространстве объекта. |
Детали
Вы можете настроить радиус ( Radius ) и высоту ( Height ) коллайдера независимо друг от друга. Это используется в компоненте Character Controller и неплохо работает для продолговатых предметов, а также можно комбинировать с другими коллайдерами для необычных форм.
Capsule Collider 2D
The Capsule Collider An invisible shape that is used to handle physical collisions for an object. A collider doesn’t need to be exactly the same shape as the object’s mesh — a rough approximation is often more efficient and indistinguishable in gameplay. More info
See in Glossary 2D is a Collider that interacts with the 2D physics system. The capsule shape has no vertex corners and has a continuous round circumference. This shape allows the Capsule Collider A capsule-shaped collider component that handles collisions for GameObjects like barrels and character limbs. More info
See in Glossary 2D to not get easily caught in the corners of other Colliders.
Note: The capsule shape of the Collider is considered solid and not hollow, which means any other Collider 2Ds that are inside the Capsule Collider 2D are considered to be in contact with the Collider and are forced out of it over time.

| Property | Function | |
|---|---|---|
| Material | Select the Physics Material 2D Use to adjust the friction and bounce that occurs between 2D physics objects when they collide More info See in Glossary that determines properties of collisions 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 , such as friction and bounce. |
|
| Is Trigger | Enable this if you want this Collider 2D to behave as a trigger. The physics system ignores this Collider when this is enabled. | |
| Used by Effector | Enable this if you want the Collider 2D to be used by an attached Effector 2D. | |
| Offset | Set the local offset values of the Collider 2D geometry. | |
| Size | Set the x and y values to define the size of the box region that the Capsule Collider 2D fills. Refer to Defining Size and Direction for more details. | |
| Direction | Select the orientation of the Capsule Collider 2D. This determines the position and orientation of the curved ends of the Collider shape. Refer to Defining Size and Direction for more details. | |
| Vertical | Select this to orient the ends of the Collider shape upwards and downwards. | |
| Horizontal | Select this to orient the ends of the Collider shape left and right. | |
| Layer Overrides | Expand for the Layer override settings. | |
| Layer Override Priority | Assign the decision priority that this Collider2D uses when resolving conflicting decisions on whether a contact between itself and another Collision2D should happen or not. Refer to its API page for more information. | |
| Include Layers | Select the additional Layers that this Collider 2D should include when deciding if a contact with another Collider2D should happen or not. Refer to its API documentation for more information. | |
| Exclude Layers | Select the additional Layers that this Collider 2D should exclude when deciding if a contact with another Collider2D should happen or not. Refer to its API documentation for more information. | |
| Force Send Layers | Select the Layers that this Collider 2D is allowed to send forces to during a Collision contact with another Collider2D. Refer to its API documentation for more information. | |
| Force Receive Layers | Select the Layers that this Collider 2D can receive forces from during a Collision contact with another Collider2D. Refer to its API documentation for more information. | |
| Contract Capture Layers | Select the Layers of other Collider 2D, involved in contacts with this Collider2D, that will be captured. Refer to its API documentation for more information. | |
| Callback Layers | Select the Layers that this Collider 2D, during a contact with another Collider2D, will report collision or trigger callbacks for. Refer to its API documentation for more information. | |
Defining Size and Direction
The settings that define the shape of the Capsule Collider 2D are Size and Direction. Both the Size and Direction properties refer to X and Y (horizontal and vertical, respectively) in the local space of the Capsule Collider 2D, and not in world space.
A typical way to set up the Capsule Collider 2D is to set the Size to match the Direction. For example, if the Capsule Collider 2D’s Direction is Vertical, the Size of X is 0.5 and the Size of Y is 1, this makes the vertical direction capsule taller, rather than wider.
In the example below, the X and Y are represented by the yellow lines.

Capsule configuration examples
You can change the Capsule Collider 2D with different configurations. Below are some examples.
Note that when the X and Y of the Size property are the same, the Capsule Collider 2D always approximates to a circle.

Note: A known issue in the 2D physics system is that when a GameObject The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary moves across multiple Colliders, one or several of the Colliders may register a collision between the Colliders. This may occur even when the Colliders are perfectly aligned. This collision can cause the Collider to slow down or stop.
While constructing a surface with the Capsule Collider 2D can help reduce this problem, it is recommeneded to use a single Collider rather than multiple Colliders for a surface, such as the Edge Collider 2D.
Composite Collider 2D
Composite Collider 2D компонент Функциональная часть GameObject. GameObject может содержать любое количество компонентов. В Unity есть много встроенных компонентов, и вы можете создавать свои собственные, написав сценарии, которые наследуются от MonoBehaviour. Подробнее
См. в Словарь – это Коллайдер Невидимая форма, используемая для обработки физических столкновений объекта. Коллайдер не обязательно должен быть точно такой же формы, как сетка объекта — грубое приближение часто бывает более эффективным и неразличимым в игровом процессе. Подробнее
См. в Словарь , который взаимодействует с системой 2D-физики. В отличие от большинства коллайдеров, он не определяет внутреннюю форму. Вместо этого он объединяет формы любого Box Collider 2D или Polygon Collider 2D, которые вы настроили для использования. . Composite Collider 2D использует вершины (геометрию) любого из этих коллайдеров и объединяет их вместе в новую геометрию, управляемую самим Composite Collider 2D.
Оба Box Collider Компонент коллайдера в форме куба, который обрабатывает коллизии игровых объектов, таких как игральные кости и кубики льда. Подробнее
См. в Словарь Компоненты 2D и Polygon Collider 2D имеют Использовано Составной флажок. Установите этот флажок, чтобы прикрепить их к Composite Collider 2D. Эти коллайдеры также должны быть прикреплены к тому же железному телу 2D, что и составной 2D-коллайдер. Когда вы включаете параметр Используется композитом, другие свойства этого компонента исчезают, так как теперь они контролируются подключенным двухмерным композитным коллайдером.
Дополнительную информацию о сценариях с помощью CompositeCollider 2D см. в документации API CompositeCollider2D.

| Свойства | Функции |
|---|---|
| Density | Измените плотность, чтобы изменить расчет массы GameObject, связанного Rigidbody Компонент, позволяющий воздействовать на GameObject смоделированной гравитацией и другими силами. Подробнее См. в Словарь 2D. Если вы установите значение 0, связанный с ним Rigidbody 2D игнорирует Collider 2D для всех расчетов масс, включая расчеты центра масс. Обратите внимание, что этот параметр доступен только в том случае, если вы включили параметр Использовать автомассу в связанном компоненте Rigidbody 2D. |
| Material | PhysicsMaterial2D Используйте для регулировки трения и отскока, возникающего между 2D-материалами. физические объекты при их столкновении Подробнее См. в Словарь , определяющий свойства класса collisions Столкновение происходит, когда физический движок обнаруживает, что коллайдеры двух игровых объектов соприкасаются или перекрываются, когда хотя бы один из них имеет компонент Rigidbody и в движении. Подробнее См. в Словарь , такие как трение и отскок. |
| Is Trigger | Установите этот флажок, если хотите, чтобы Composite Collider 2D вел себя как триггер (см. обзорную документацию по коллайдерам, чтобы узнать больше о триггерах). |
| Used by Effector | Установите этот флажок, если хотите, чтобы Composite Collider 2D использовался присоединенным компонентом Effector 2D. |
| Offset | Установите локальное смещение двухмерной геометрии коллайдера. |
| Geometry Type | При объединении коллайдеров вершины из выбранных коллайдеров объединяются в один из двух разных типов геометрии. Используйте это раскрывающееся меню, чтобы задать тип геометрии: Контуры или Многоугольники. |
| Outlines | Создает 2D-коллайдер с полыми контурами, идентичный тому, что создает 2D-коллайдер. |
| Polygons | Создает 2D-коллайдер со сплошными многоугольниками, идентичный тому, что создает 2D-полигональный коллайдер. |
| Generation Type | Метод, используемый для управления генерацией геометрии при изменении двухмерного композитного коллайдера или любого из составляющих его коллайдеров. |
| Synchronous | Когда в Composite Collider 2D или любом из используемых им коллайдеров вносятся изменения, Unity немедленно генерирует новую геометрию. |
| Manual | Генерация новой геометрии происходит только по запросу. Чтобы запросить генерацию, либо вызовите API скрипта CompositeCollider2D.GenerateGeometry, либо нажмите кнопку Regenerate Geometry, которая появляется под выбором . |
| Vertex Distance | Установите значение минимального интервала, разрешенного для любых вершин, собранных из составных коллайдеров. Любая вершина ближе этого предела удаляется. Это позволяет контролировать эффективное разрешение компоновки вершин. |
| Edge Radius | Управляет радиусом вокруг ребер, чтобы вершины были круглыми. Это приводит к большему коллайдеру 2D с закругленными выпуклыми углами. Значение по умолчанию для этого параметра равно 0 (без радиуса). Это работает, только если для параметра Тип геометрии установлено значение Контуры. |
Не работает коллайдер с 2D объектами

При попытки столкновения, персонаж проходит сквозь квадрат:
Проверил функцией столкновения OnTriggerEnter2D(); квадрат:
void OnTriggerEnter2D(Collider2D collision)

Отслеживать
задан 2 ноя 2022 в 20:09
669 8 8 серебряных знаков 18 18 бронзовых знаков
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Возможно проблема в канвасе. Канвас для UI. Для геймплея и физики — мировое простанство.
Отслеживать
ответ дан 2 ноя 2022 в 20:28
Александр Даниловский Александр Даниловский
1,284 2 2 золотых знака 8 8 серебряных знаков 11 11 бронзовых знаков
Не совсем понял..
2 ноя 2022 в 20:44
Судя по видео, ты хочешь использовать физику в канвасе. Т.е. игру, геймплейные механики, ты хочешь делать в канвасе. Во-первых, это неправильно. Во-вторых, возможно из-за канваса физика не работает, кроме триггеров (это предположение)
2 ноя 2022 в 20:48
Убрал канвас, всё равно не помогает. Сейчас попробую другую сцену создам. Я думал канвас используется для того, чтобы все элементы подходили под любое разрешение экрана, а оказывается от для UI..