Is trigger unity что это
Перейти к содержимому

Is trigger unity что это

  • автор:

Introduction to collision

Unity handles collision between GameObjects with colliders, which attach to GameObjects and define the shape of 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 for the purposes of physical collisions. A collider is invisible, and does not need to be the exact same shape as the GameObject’s mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary . 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 A cube-shaped collider component that handles collisions for GameObjects like dice and ice cubes. More info
See in Glossary , Sphere Collider A sphere-shaped collider component that handles collisions for GameObjects like balls or other things that can be roughly approximated as a sphere for the purposes of physics. More info
See in Glossary and Capsule Collider A capsule-shaped collider component that handles collisions for GameObjects like barrels and character limbs. More info
See in Glossary . 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 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.

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 A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary . 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 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. A slippery material like ice, for example, has zero (or very low) friction. A grippy material like rubber has 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

The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine A system that simulates aspects of physical systems so that objects can accelerate correctly and be affected by collisions, gravity and other forces. More info
See in Glossary 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 A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary .

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

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 move normally 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.

Collider’s and Triggers in Unity — Understanding the Basics

Chris Hilton

Objective: Understanding the basics of how Colliders and Triggers work.

Continuing to build this Galaxy Shooter game, I am now up to a point where I require my game objects to be colliding and interacting with each other and need to decide which method between OnCollisionEnter and OnTriggerEnter is going to function best. I need my Laser that is shot from the Player to interact with the Enemy and I also need the Enemy to interact with the Player if they collide, but I am not interested in having my game objects simulate the effects of physics on their Rigidbodies as I am planning to create an explosion effect and have the game object disappear. Let’s start by looking into a Collider and a Trigger:

Collider Vs Trigger

Colliders are Components that are built into Unity which provide collision detection through the various green lines (or boundaries). They define the shape of game objects for the purposes of physical collision. There must also be one Rigidbody attached to one of the game objects. In the example below we can see a simple 3D cube with the green border lines around it, this is a simple Box Collider. This can be manipulated to be larger or smaller than the box depending on the objective for your game and how you want Unity’s Colliders to interact with each other utilising Unity’s physics system. Multiple Colliders can be added to a single game object and Unity also provides simple primitive Colliders such as Box, Sphere, Circle and Capsule.

Let’s turn our Gravity off on the Rigidbody as I won’t be using this in my game:

The 2 game objects are going to Destroy once they collide:

Unity3d. Уроки от Unity 3D Student (B13-B16)

PS: Так же исправленны некоторые ошибки в предыдущих уроках, большое спасибо хабравчанинам ufomesh и MikhailS.

Базовый Урок 13 — Определение столкновений с триггером

В уроке рассказывается, как определить столкновения между невидимыми для игрока объектами, используя неосязаемые «триггер коллайдеры» (trigger colliders).

Если вы хотите определить столкновения, но не ходите, чтоб столкнувшийся объект остановился, вам требуется использовать триггер (trigger)

Триггеры позволяют вам определить, где именно расположен объект на сцене (во время запуска приложения).

На нашей сцене имеется куб («box» с rigidbody), который падает на синюю платформу («platform»).
b1300
b1301

Естественно платформа останавливает куб, поскольку среди ее компонентов присутствует box collider.
b1302

У компонента box collider есть чекбокc Is Trigger. Если включить
его и запустить сцену снова, то куб провалиться через платформу.
b1303

Таким образом мы можем создавать столкновения, которые не должны быть видны пользователю. Например, отключим компонент Mesh Renderer у нашей платформы. Мы по прежнему видем зеленый контур объекта, если выделим его в Hierarchy View.
b1304

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

Создадим скрипт, назовем его Trigger и добавим в тело класса следующий код

Добавим скрипт к платформе. Теперь, как тольку куб пройдет сквозь платформу, вы увидете сообщение «Box went through!» в консоли.

Базовый Урок 14 — GUI текст и счетчики

В уроке рассказывается, как отобразить информацию о счетчике на экран используя компонент GUI Text

Чтобы отображать текстовую информацию на экран воспользуемся элементом GUI Text.
Добавим его на сцену — Game Object->Create Other->GUI Text.
b1400

Так же, обратите внимание, чтоб у камеры был включен компонент GUILayer.
b1401

Текст можно редактировать напрямую через редактор (поле Text).
b1402

Но мы воспользуемся скриптом для этого. Добавим скрипт (GUITextExample). Код будем писать в метод Update():

Если зайти в стравку о параметре guiText.text, то увидите следующие:
var text: String
Description
The text to display.

То есть, при передачи параметра мы должны быть уверены что передаем string.

Теперь если запустить игру, то текст поменяется.
b1403

Попробуем отобразить счетчик. В класс добавим переменную-счетчик (Counter) и немного подправим код в методе Update().

В итоге Unity выдаст ошибку:

Нам требуется привести переменную типа int к типу string.
Это можно сделать многими способами. Вот некоторые из них:

Воспользуемся последним способом, только вместо пустой строки напишем текст:

Жмем play и наблюдаем как увеличивается значения переменной-счетчика.
b1404

Мы так же можем изменить шрифт текста, если у вас в проекте есть дополнительный шрифт (font).

Чтоб поменять шрифт, достаточно перетащить его в соответствующие поле компонента GUIText (Font).
b1405

Тут же можно поменять другие параметры, такие как размер (font size), выравнивание (alignment) и некоторые другие.

Базовый Урок 15 — Добавление компонентов с помощью скриптов

В уроке рассказывается, как добавить компонент к объекту используя скрипты и быть увереным, что мы их добавили только однажды.

Для того, чтобы добавить компонент в run-time воспользуемся скриптами.
В нашем примере у нас снова есть платформа («platform») и ящик(«box» с rigidbody) который на нее падает.

Попробуем добивать компонент к платформе, как только ящик упадёт на неё.
Добавим скрипт addComp В класс добивим следующий код:

Скрипт добавим к ящику. Жмем play и видим — как только ящик падает на платформа, она тоже начнёт падать.

Но в консоле вы увидите предупреждение:

Мы получили это сообщение, поскольку пытаемся добавить компонент Rigidbody каждый раз, когда ящик сталкивается с платформой, то есть — мы добавляем его более одного раза. Чтоб этого не происходило, нам нужно добавить проверку и добавлять компонент, только в случае его отсутствия. Добавим в OnCollisionEnter() еще одно условие:

Теперь запустим приложение и убедимся, что в консоли отсутствует предупреждение.

Базовый Урок 16 — Переключение между сцен

В уроке рассказывается, как написать скрипт, для переключения между сценами в проекте Unity.

Для полноценной работы с Unity нужно уметь переключаться между различными сценами, для загрузки разных уровней, меню и другого контента. Для этого воспользуемся методом LoadLevel() класса Application.

В нашем примере есть 2е сцены. Первая («Level») — с кубом и плоскостью («floor»), на которую куб падает.Вторая («gameover») — с зеленым фотон и GUI Text’ом — «YOU WIN!»
b1600
b1601

Добавим скрипт (LoadLevel) со следующим кодом:

Жмем play. В итоге в консоли появилась ошибка:

Дело в том, что когда мы работаем с классом Application, мы должны указывать в настройках сборки (Build Settings) все сцены, которые хотим загружать в итоговом приложении. Перейдем в настройки сборки File->Build Settings и перетащим сцены Level и gameover из Project View в верхнее поле Buil Settings
b1602

Немного подредактируем наш скрипт так, чтоб мы могли указывать имя уровня из окна редактора, таким образом мы делаем наш скрипт более «гибким».

В окне редактора, на против соответствующего поля компонента, напишем название сцены, которую хотим загрузить.
b1603

Unity Collision 2D and 3D: Super Simple Guide

Collision detection is required for all types of games and is one of the major components to know if you want to learn Unity. Unity Collision works based on the collider component that can be added to any game object. Also, you need to understand how colliders and Unity 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

A Collider in Unity, defines the boundary of a game object. The shape of the collider is depended on the type of collider used. Colliders can also be classified with respect to physics, depending on how they interact with other objects.

Also, Unity has divided the colliders into 2D and 3D. So, you have to be very careful which collider you are using. All your codes and collision detection will change to 2D and 3D.

Unity Collider Types based on Physics

Static collider

Static colliders are considered to be non-moving objects by Unity. Do not confuse static game object 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.

Rigidbody collider or Dynamic 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 needs to be affected by physics laws.

Kinematic Rigidbody collider

A kinematic Rigidbody collider is a Rigidbody that behaves like a static object but can be converted into a dynamic collider at point of the game.

3D collider shapes in Unity

Collider shape Where to use Effect on Performance
Box Collider Object shaped like cube Less Performance intensive
Sphere Collider 3D round shaped objects Less Performance intensive
Capsule Colliders For Characters Less Performance intensive
Mesh Colliders Objects with Uneven shapes Performance intensive
Terrain Colliders For Unity terrains Very Performance intensive

Adding a 3D collider in Unity

To add a collider to your game object, select the object in Hierarchy view and click on Add Component in the Inspector window. Then select the type of Collider based on your requirement.

You can adjust the size of the collider using the Edit Collider button.

Unity Collider component add to a game 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.

Non-trigger Colliders

When a collider is not marked as Trigger, Unity will detect a collision only if one of the objects is a Rigidbody. That is, if you have two game object marked as static colliders then collision between them will not be detected.

It’s the same case with two kinematic Rigidbodies. Find the collision matrix for non-trigger Unity colliders in the image below.

collision matrix for Non trigger unity colliders

On Collision Enter Function

To detect the collision, we can use the OnCollisionEnter() . This function is called when a collision between non-trigger colliders is detected.

The function contains all details of the collision. You can get the following details for the collision variable.

Properties of OnCollisionEnter() Description
collider The Collider that was hit.
contactCount Number of contacts for this collision.
gameObject The collider game object
relativeVelocity The relative linear velocity of the two colliding objects.
rigidbody The Rigidbody attached to the collider.
transform The Transform of the object we hit.

Along with the above properties, there are two more functions that we can access. One is GetContact and the other is GetContacts .

GetContact returns a single point from the contacts array and GetContacts returns an array of all contact points.

Here is an example code on how to use OnCollisionEnter() to destroy the object that we hit, if it has an Enemy tag.

Unity Trigger collider

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. A trigger collider can collide with a kinematic Rigidbody. Here is the collision matrix for trigger colliders.

Trigger collision matrix

On Trigger Enter function

Trigger collision doesn’t work in Unity if both the colliders are static colliders. In all the other cases the OnTriggerEnter function is called. Unlike OnCollisionEnter , you cannot get the collision parameters in this case. But there are some properties that you can use.

gameObject The game object that we hit
tag The tag of the game object that we hit.
transform The Transform of Game Object that we hit.
name The name of the Game Object that we hit.

Here is an example of how to use OnTriggerEnter to destroy the object that we hit, if it has an Enemy tag.

Summarizing collision matrix

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 normally, collision is detected only if one of the game objects is movable by physics. Whereas trigger function works little differently. It works only if one of the colliders is marked as trigger and both objects are not static.

Setting Collision Layers in Unity

One you have added your colliders and Rigidbody now it’s time to set the layers. Unity gives you control to decide which layers collide with each other.

This setting is available in Edit>Project settings> Physics.

Layer collision setting in Unity

You can just uncheck the layers that you don’t want to collide with. For example, if you don’t want the friend layer to collide with the water layer. Then just uncheck the box in water row of the Friend column.

Remember to create all your layers first before editing this setting.

Other Unity Collider functions

There are few more functions to detect whether the game object has exited the collision phase 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 Detection 2D

Collision in 2D is very similar to 3D, but there is a change in terminology. When it comes to 2D, Unity has put in a lot of effort to distinguish 2D colliders from 3D.

2D Collision in Unity uses Physics2D engine. Everything in Physics2D has a suffix 2D added to it. It’s a physics engine on its own but for the 2D world.

Adding a 2D collider

Select your game object and click on Add Component in the inspector window. Add a 2D collider from the component list.

3D vs 2D collider Terminologies

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

2D Collision layer setting in Unity

Similar to 3D you can decide which layers will collide with each other in physics 2D.

To set this you have to go to Edit>Project settings>Physics2D.

Layer Collision matrix 2D

Functions in Unity Collision 2D

OnCollisionEnter2D

This can be used to detect collision between two colliders that are not set as Trigger and at least one of them has a Rigidbody attached to it.

OnTriggerEnter2D

OnTiggerEnter2D is used to detect collision between 2D colliders that are set as a trigger. You need to use this, even if one of the Collider is set as Trigger.

Other Unity 2D collider functions

Non-Trigger 2D Collision

  • OnCollisionExit2D- Is called when the Collider2D exits a Collision.
  • OnCollisionStay2D – Is called when the Collider2D is still colliding with another object.

Trigger 2D Collision

  • OnTriggerExit2D- Is called when the Trigger Collider2D exits a Collision.
  • OnTriggerStay2D- Is called when the Trigger Collider2D is still colliding with another object.
Sample script for 2D collision detection functions

That summarizes the collider function in Unity. If you have any questions, you can post it in the comment box below. Next, we will learn how to add components using scripts.

Unity3d. Уроки от Unity 3D Student (B13-B16)

PS: Так же исправленны некоторые ошибки в предыдущих уроках, большое спасибо хабравчанинам ufomesh и MikhailS.

Базовый Урок 13 — Определение столкновений с триггером

В уроке рассказывается, как определить столкновения между невидимыми для игрока объектами, используя неосязаемые «триггер коллайдеры» (trigger colliders).

Если вы хотите определить столкновения, но не ходите, чтоб столкнувшийся объект остановился, вам требуется использовать триггер (trigger)

Триггеры позволяют вам определить, где именно расположен объект на сцене (во время запуска приложения).

На нашей сцене имеется куб («box» с rigidbody), который падает на синюю платформу («platform»).
b1300
b1301

Естественно платформа останавливает куб, поскольку среди ее компонентов присутствует box collider.
b1302

У компонента box collider есть чекбокc Is Trigger. Если включить
его и запустить сцену снова, то куб провалиться через платформу.
b1303

Таким образом мы можем создавать столкновения, которые не должны быть видны пользователю. Например, отключим компонент Mesh Renderer у нашей платформы. Мы по прежнему видем зеленый контур объекта, если выделим его в Hierarchy View.
b1304

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

Создадим скрипт, назовем его Trigger и добавим в тело класса следующий код

Добавим скрипт к платформе. Теперь, как тольку куб пройдет сквозь платформу, вы увидете сообщение «Box went through!» в консоли.

Базовый Урок 14 — GUI текст и счетчики

В уроке рассказывается, как отобразить информацию о счетчике на экран используя компонент GUI Text

Чтобы отображать текстовую информацию на экран воспользуемся элементом GUI Text.
Добавим его на сцену — Game Object->Create Other->GUI Text.
b1400

Так же, обратите внимание, чтоб у камеры был включен компонент GUILayer.
b1401

Текст можно редактировать напрямую через редактор (поле Text).
b1402

Но мы воспользуемся скриптом для этого. Добавим скрипт (GUITextExample). Код будем писать в метод Update():

Если зайти в стравку о параметре guiText.text, то увидите следующие:
var text: String
Description
The text to display.

То есть, при передачи параметра мы должны быть уверены что передаем string.

Теперь если запустить игру, то текст поменяется.
b1403

Попробуем отобразить счетчик. В класс добавим переменную-счетчик (Counter) и немного подправим код в методе Update().

В итоге Unity выдаст ошибку:

Нам требуется привести переменную типа int к типу string.
Это можно сделать многими способами. Вот некоторые из них:

Воспользуемся последним способом, только вместо пустой строки напишем текст:

Жмем play и наблюдаем как увеличивается значения переменной-счетчика.
b1404

Мы так же можем изменить шрифт текста, если у вас в проекте есть дополнительный шрифт (font).

Чтоб поменять шрифт, достаточно перетащить его в соответствующие поле компонента GUIText (Font).
b1405

Тут же можно поменять другие параметры, такие как размер (font size), выравнивание (alignment) и некоторые другие.

Базовый Урок 15 — Добавление компонентов с помощью скриптов

В уроке рассказывается, как добавить компонент к объекту используя скрипты и быть увереным, что мы их добавили только однажды.

Для того, чтобы добавить компонент в run-time воспользуемся скриптами.
В нашем примере у нас снова есть платформа («platform») и ящик(«box» с rigidbody) который на нее падает.

Попробуем добивать компонент к платформе, как только ящик упадёт на неё.
Добавим скрипт addComp В класс добивим следующий код:

Скрипт добавим к ящику. Жмем play и видим — как только ящик падает на платформа, она тоже начнёт падать.

Но в консоле вы увидите предупреждение:

Мы получили это сообщение, поскольку пытаемся добавить компонент Rigidbody каждый раз, когда ящик сталкивается с платформой, то есть — мы добавляем его более одного раза. Чтоб этого не происходило, нам нужно добавить проверку и добавлять компонент, только в случае его отсутствия. Добавим в OnCollisionEnter() еще одно условие:

Теперь запустим приложение и убедимся, что в консоли отсутствует предупреждение.

Базовый Урок 16 — Переключение между сцен

В уроке рассказывается, как написать скрипт, для переключения между сценами в проекте Unity.

Для полноценной работы с Unity нужно уметь переключаться между различными сценами, для загрузки разных уровней, меню и другого контента. Для этого воспользуемся методом LoadLevel() класса Application.

В нашем примере есть 2е сцены. Первая («Level») — с кубом и плоскостью («floor»), на которую куб падает.Вторая («gameover») — с зеленым фотон и GUI Text’ом — «YOU WIN!»
b1600
b1601

Добавим скрипт (LoadLevel) со следующим кодом:

Жмем play. В итоге в консоли появилась ошибка:

Дело в том, что когда мы работаем с классом Application, мы должны указывать в настройках сборки (Build Settings) все сцены, которые хотим загружать в итоговом приложении. Перейдем в настройки сборки File->Build Settings и перетащим сцены Level и gameover из Project View в верхнее поле Buil Settings
b1602

Немного подредактируем наш скрипт так, чтоб мы могли указывать имя уровня из окна редактора, таким образом мы делаем наш скрипт более «гибким».

В окне редактора, на против соответствующего поля компонента, напишем название сцены, которую хотим загрузить.
b1603

Collider’s and Triggers in Unity — Understanding the Basics

Chris Hilton

Objective: Understanding the basics of how Colliders and Triggers work.

Continuing to build this Galaxy Shooter game, I am now up to a point where I require my game objects to be colliding and interacting with each other and need to decide which method between OnCollisionEnter and OnTriggerEnter is going to function best. I need my Laser that is shot from the Player to interact with the Enemy and I also need the Enemy to interact with the Player if they collide, but I am not interested in having my game objects simulate the effects of physics on their Rigidbodies as I am planning to create an explosion effect and have the game object disappear. Let’s start by looking into a Collider and a Trigger:

Collider Vs Trigger

Colliders are Components that are built into Unity which provide collision detection through the various green lines (or boundaries). They define the shape of game objects for the purposes of physical collision. There must also be one Rigidbody attached to one of the game objects. In the example below we can see a simple 3D cube with the green border lines around it, this is a simple Box Collider. This can be manipulated to be larger or smaller than the box depending on the objective for your game and how you want Unity’s Colliders to interact with each other utilising Unity’s physics system. Multiple Colliders can be added to a single game object and Unity also provides simple primitive Colliders such as Box, Sphere, Circle and Capsule.

Let’s turn our Gravity off on the Rigidbody as I won’t be using this in my game:

The 2 game objects are going to Destroy once they collide:

Unity Collision 2D and 3D: Super Simple Guide

Collision detection is required for all types of games and is one of the major components to know if you want to learn Unity. Unity Collision works based on the collider component that can be added to any game object. Also, you need to understand how colliders and Unity 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

A Collider in Unity, defines the boundary of a game object. The shape of the collider is depended on the type of collider used. Colliders can also be classified with respect to physics, depending on how they interact with other objects.

Also, Unity has divided the colliders into 2D and 3D. So, you have to be very careful which collider you are using. All your codes and collision detection will change to 2D and 3D.

Unity Collider Types based on Physics

Static collider

Static colliders are considered to be non-moving objects by Unity. Do not confuse static game object 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.

Rigidbody collider or Dynamic 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 needs to be affected by physics laws.

Kinematic Rigidbody collider

A kinematic Rigidbody collider is a Rigidbody that behaves like a static object but can be converted into a dynamic collider at point of the game.

3D collider shapes in Unity

Collider shape Where to use Effect on Performance
Box Collider Object shaped like cube Less Performance intensive
Sphere Collider 3D round shaped objects Less Performance intensive
Capsule Colliders For Characters Less Performance intensive
Mesh Colliders Objects with Uneven shapes Performance intensive
Terrain Colliders For Unity terrains Very Performance intensive

Adding a 3D collider in Unity

To add a collider to your game object, select the object in Hierarchy view and click on Add Component in the Inspector window. Then select the type of Collider based on your requirement.

You can adjust the size of the collider using the Edit Collider button.

Unity Collider component add to a game 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.

Non-trigger Colliders

When a collider is not marked as Trigger, Unity will detect a collision only if one of the objects is a Rigidbody. That is, if you have two game object marked as static colliders then collision between them will not be detected.

It’s the same case with two kinematic Rigidbodies. Find the collision matrix for non-trigger Unity colliders in the image below.

collision matrix for Non trigger unity colliders

On Collision Enter Function

To detect the collision, we can use the OnCollisionEnter() . This function is called when a collision between non-trigger colliders is detected.

The function contains all details of the collision. You can get the following details for the collision variable.

Properties of OnCollisionEnter() Description
collider The Collider that was hit.
contactCount Number of contacts for this collision.
gameObject The collider game object
relativeVelocity The relative linear velocity of the two colliding objects.
rigidbody The Rigidbody attached to the collider.
transform The Transform of the object we hit.

Along with the above properties, there are two more functions that we can access. One is GetContact and the other is GetContacts .

GetContact returns a single point from the contacts array and GetContacts returns an array of all contact points.

Here is an example code on how to use OnCollisionEnter() to destroy the object that we hit, if it has an Enemy tag.

Unity Trigger collider

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. A trigger collider can collide with a kinematic Rigidbody. Here is the collision matrix for trigger colliders.

Trigger collision matrix

On Trigger Enter function

Trigger collision doesn’t work in Unity if both the colliders are static colliders. In all the other cases the OnTriggerEnter function is called. Unlike OnCollisionEnter , you cannot get the collision parameters in this case. But there are some properties that you can use.

gameObject The game object that we hit
tag The tag of the game object that we hit.
transform The Transform of Game Object that we hit.
name The name of the Game Object that we hit.

Here is an example of how to use OnTriggerEnter to destroy the object that we hit, if it has an Enemy tag.

Summarizing collision matrix

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 normally, collision is detected only if one of the game objects is movable by physics. Whereas trigger function works little differently. It works only if one of the colliders is marked as trigger and both objects are not static.

Setting Collision Layers in Unity

One you have added your colliders and Rigidbody now it’s time to set the layers. Unity gives you control to decide which layers collide with each other.

This setting is available in Edit>Project settings> Physics.

Layer collision setting in Unity

You can just uncheck the layers that you don’t want to collide with. For example, if you don’t want the friend layer to collide with the water layer. Then just uncheck the box in water row of the Friend column.

Remember to create all your layers first before editing this setting.

Other Unity Collider functions

There are few more functions to detect whether the game object has exited the collision phase 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 Detection 2D

Collision in 2D is very similar to 3D, but there is a change in terminology. When it comes to 2D, Unity has put in a lot of effort to distinguish 2D colliders from 3D.

2D Collision in Unity uses Physics2D engine. Everything in Physics2D has a suffix 2D added to it. It’s a physics engine on its own but for the 2D world.

Adding a 2D collider

Select your game object and click on Add Component in the inspector window. Add a 2D collider from the component list.

3D vs 2D collider Terminologies

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

2D Collision layer setting in Unity

Similar to 3D you can decide which layers will collide with each other in physics 2D.

To set this you have to go to Edit>Project settings>Physics2D.

Layer Collision matrix 2D

Functions in Unity Collision 2D

OnCollisionEnter2D

This can be used to detect collision between two colliders that are not set as Trigger and at least one of them has a Rigidbody attached to it.

OnTriggerEnter2D

OnTiggerEnter2D is used to detect collision between 2D colliders that are set as a trigger. You need to use this, even if one of the Collider is set as Trigger.

Other Unity 2D collider functions

Non-Trigger 2D Collision

  • OnCollisionExit2D- Is called when the Collider2D exits a Collision.
  • OnCollisionStay2D – Is called when the Collider2D is still colliding with another object.

Trigger 2D Collision

  • OnTriggerExit2D- Is called when the Trigger Collider2D exits a Collision.
  • OnTriggerStay2D- Is called when the Trigger Collider2D is still colliding with another object.
Sample script for 2D collision detection functions

That summarizes the collider function in Unity. If you have any questions, you can post it in the comment box below. Next, we will learn how to add components using scripts.

Introduction to collision

Unity handles collision between GameObjects with colliders, which attach to GameObjects and define the shape of 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 for the purposes of physical collisions. A collider is invisible, and does not need to be the exact same shape as the GameObject’s mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary . 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 A cube-shaped collider component that handles collisions for GameObjects like dice and ice cubes. More info
See in Glossary , Sphere Collider A sphere-shaped collider component that handles collisions for GameObjects like balls or other things that can be roughly approximated as a sphere for the purposes of physics. More info
See in Glossary and Capsule Collider A capsule-shaped collider component that handles collisions for GameObjects like barrels and character limbs. More info
See in Glossary . 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 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.

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 A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary . 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 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. A slippery material like ice, for example, has zero (or very low) friction. A grippy material like rubber has 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

The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine A system that simulates aspects of physical systems so that objects can accelerate correctly and be affected by collisions, gravity and other forces. More info
See in Glossary 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 A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary .

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

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 move normally 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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *