collider unity что это такое
Меш-коллайдер (Mesh Collider)
Mesh Collider использует меш ассет для создания под него коллайдера на основе этого меша. Это гораздо удобнее, чем использовать примитивы для определения столкновений сложных мешей. Меш коллайдеры, которые помечены как Convex могут взаимодействовать (сталкиваться) с другими меш коллайдерами.
Свойства
Свойство: | Функция: |
---|---|
Is Trigger | Если включён, то этот коллайдер будет игнорироваться физическим движком и использоваться для запуска событий. |
Material | Ссылка на физический материал, который определяет, как данный коллайдер взаимодействует с другими. |
Mesh | Ссылка на меш, используемый для столкновений. |
Convex | При включении, текущий меш коллайдер будет взаимодействовать с другими меш коллайдерами. Выпуклые (Convex) меш коллайдеры ограничены 255 треугольниками. |
Детали
The Mesh Collider builds its collision representation from the Mesh attached to the GameObject, and reads the properties of the attached Transform to set its position and scale correctly. The benefit of this is that the shape of the collider can be exactly the same as the shape of the visible mesh for the object, resulting in more precise and authentic collisions. However, this precision comes with a higher processing overhead than collisions involving primitive colliders (sphere, box, capsule) and so it is best to use Mesh Colliders sparingly.
Меши, служащие для расчёта столкновений, используют отсечение невидимых поверхностей. Если объект столкнётся с таким мешем визуально, то он также столкнётся с ним и физически.
Note that versions of Unity before 5.0 had a Smooth Sphere Collisions property for the Mesh Collider in order to improve interactions between meshes and spheres. This property is now obsolete since the smooth interaction is standard behaviour for the physics engine and there is no particular advantage in switching it off.
Коллайдеры (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.
Однако существуют случаи, где даже составные коллайдеры недостаточно точны. В 3D вы можете использовать Mesh Colliders, чтобы создать коллайдер, идентичный по форме мешу объекта. В 2D Polygon Collider 2D сгенерирует форму примерно совпадающую с графикой спрайта. Не идеально, но вы можете изменить его форму до любого уровня детализации. Эти коллайдеры нагружают процессор сильнее, чем примитивные коллайдеры, так что используйте их экономно, чтобы сохранить высокую производительность. Также Mesh Collider не сможет сталкиваться с другими Mesh Collider (другими словами, при их контакте ничего не произойдёт). В некоторых случаях вы можете обойти это пометив Mesh Collider в инспекторе как Convex (выпуклый). Это создаст коллайдер формы “выпуклой оболочки”, который такой же, как и оригинальный меш, но с “заполненными” углублениями. Польза от этого в том, что выпуклый Mesh Collider может сталкиваться с другими Mesh Collider, так что вы сможете использовать эту функцию, когда у вас есть двигающийся персонаж с подходящей формой. Тем не менее хорошим общим правилом будет использование Mesh Collider для геометрии сцены, и имитировать приближённую к реальности форму для двигающихся объектов с помощью примитивных коллайдеров.
Для создания пола, стен и других неподвижных элементов сцены, к объектам без компонента Rigidbody можно добавлять коллайдеры. Они называются static (статичными) коллайдерами. Обычно вам не следует перемещать статичные коллайдеры изменяя положение их трансформации, т.к. это сильно повлияет на производительность физического движка. Коллайдеры на объекте, у которого есть Rigidbody, известны как динамичные коллайдеры. Статичные коллайдеры могут взаимодействовать с динамичными коллайдерами, но, т.к. у них нету Rigidbody, они не сдвинутся в ответ на коллизии (столкновения).
Страницы справки для различных типов коллайдеров, указанных выше, имеют дополнительную информацию об их свойствах и способах использования.
Физические материалы (Physics Materials)
Когда коллайдеры взаимодействуют, их поверхностям надо симулировать свойства материала, из которого они теоретически должны состоять. Например, слой льда будет более скользким, в то время как резиновый мяч будет предлагать больше трения и будет очень упругим. Хотя форма коллайдеров и не деформируется во время коллизий, их трение и упругость можно настроить используя физические материалы (Physics Materials). Настроить параметры так, как хочется, можно методом проб и ошибок, но, например, материал льда будет иметь нулевое (или очень маленькое) трение, а резиновый материал будет с большим показателем трения и почти идеальной упругостью. Для дополнительной информации по доступным параметрам, читайте страницы справки Physic Material и Physics Material 2D. Учтите, что, по историческим причинам, 3D ассет называется Physic Material, в то время как 2D эквивалент называется Physics Material 2D (с “s” после “Physic”).
Триггеры (Triggers)
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.
У обычных не триггерных коллизий есть ещё дополнительная деталь: как минимум один из вовлечённых в коллизию объектов должен обладать не кинематическим Rigidbody (т.е. IsKinematic должен быть выключен). Если оба объекта являются кинематическими, то тогда не будут вызываться функции, вроде OnCollisionEnter и т.д. С триггерными столкновениями это условие не применяется, так что и кинематические и не кинематические Rigidbody будут незамедлительно вызывать OnTriggerEnter при пересечении триггерного коллайдера.
Взаимодействия коллайдеров
Коллайдеры взаимодействуют друг с другом по разному, в зависимости от того, как настроены их компоненты Rigidbody. Тремя важными конфигурациями являются статичный коллайдер (Static Collider) (т.е. компонент Rigidbody отсутствует вообще), Rigidbody коллайдер (Rigidbody Collider), и кинематический Rigidbody коллайдер (Kinematic Rigidbody Collider).
Статичный коллайдер (Static Collider)
Это игровой объект, у которого есть коллайдер, но нету Rigidbody. Статичные коллайдеры используются для геометрии уровней, которая всегда стоит на месте и совсем не двигается. Встречные Rigidbody объекты будут врезаться в статичный коллайдер, но его не сдвинут.
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 коллайдер (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.
Матрица действий коллизии
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
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.
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
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 A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary 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 A free-form collider component which accepts a mesh reference to define its collision surface shape. More info
See in Glossary to match the shape of the GameObject’s mesh exactly. In 2D, the Polygon Collider 2D does not match the shape of the 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 graphic perfectly but you can refine the shape to any level of detail The Level Of Detail (LOD) technique is an optimization that reduces the number of triangles that Unity has to render for a GameObject when its distance from the Camera increases. More info
See in Glossary you like.
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 A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary 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
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 A physics asset for adjusting the friction and bouncing effects of colliding objects. More info
See in Glossary (without the S) but the 2D equivalent is called Physics Material 2D Use to adjust the friction and bounce that occurs between 2D physics objects when they collide More info
See in Glossary (with the S).
Triggers
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.
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
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
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 A Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform. More info
See in Glossary 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.