Raycast unity что это
Physics2D.Raycast
Parameters
origin | @param origin Стартовая точка фигуры в 2D пространстве. |
direction | A vector representing the direction of the ray. |
distance | The maximum distance over which to cast the ray. |
layerMask | @param layerMask Фильтр для обнаружения коллайдеров только на определённых слоях. |
minDepth | @param minDepth Включает только объекты с координатой Z (глубиной) выше, чем это значение. |
maxDepth | @param maxDepth Включает только объекты с координатой Z (глубиной) меньше, чем это значение. |
Returns
RaycastHit2D The cast results returned.
Description
Casts a ray against colliders in the Scene.
BoxCast, концептуально, это как протягивание коробки сквозь сцену в определенном направлении. Любой объект, вступающий в контакт с коробкой, может быть обнаружен и зарегистрирован.
This function returns a RaycastHit object with a reference to the collider that is hit by the ray (the collider property of the result will be NULL if nothing was hit). The layerMask can be used to detect objects selectively only on certain layers (this allows you to apply the detection only to enemy characters, for example).
Overloads of this method that use contactFilter can filter the results by the options available in ContactFilter2D.
Raycasts are useful for determining lines of sight, targets hit by gunfire and for many other purposes in gameplay.
Additionally, this will also detect Collider(s) at the start of the ray. In this case, the ray starts inside the Collider and doesn’t intersect the Collider surface. This means that the collision normal cannot be calculated, in which case the returned collision normal is set to the inverse of the ray vector being tested. This can easily be detected because such results are always at a RaycastHit2D fraction of zero.
Parameters
origin | @param origin Стартовая точка фигуры в 2D пространстве. |
direction | A vector representing the direction of the ray. |
contactFilter | The contact filter used to filter the results differently, such as by layer mask, Z depth, or normal angle. |
results | The array to receive results. The size of the array determines the maximum number of results that can be returned. |
distance | The maximum distance over which to cast the ray. |
Returns
int Returns the number of results placed in the results array.
Description
Casts a ray against colliders in the Scene.
BoxCast, концептуально, это как протягивание коробки сквозь сцену в определенном направлении. Любой объект, вступающий в контакт с коробкой, может быть обнаружен и зарегистрирован.
Parameters
origin | @param origin Стартовая точка фигуры в 2D пространстве. |
direction | A vector representing the direction of the ray. |
contactFilter | The contact filter used to filter the results differently, such as by layer mask, Z depth, or normal angle. |
results | The list to receive results. |
distance | The maximum distance over which to cast the ray. |
Returns
int Returns the number of results placed in the results list.
Description
Casts a ray against Colliders in the Scene.
A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any Collider making contact with the beam can be detected and reported.
The integer return value is the number of results written into the results list. The results list will be resized if it doesn’t contain enough elements to report all the results. This prevents memory from being allocated for results when the results list does not need to be resized, and improves garbage collection performance when the query is performed frequently.
Physics.Raycast
Success!
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
Submission failed
For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
Declaration
Parameters
origin | The starting point of the ray in world coordinates. |
direction | The direction of the ray. |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore Colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Returns
bool Returns true if the ray intersects with a Collider, otherwise false.
Description
You may optionally provide a LayerMask, to filter out any Colliders you aren’t interested in generating collisions with.
Specifying queryTriggerInteraction allows you to control whether or not Trigger colliders generate a hit, or whether to use the global Physics.queriesHitTriggers setting.
Notes: Raycasts will not detect Colliders for which the Raycast origin is inside the Collider. In all these examples FixedUpdate is used rather than Update. Please see Order of Execution for Event Functions to understand the difference between Update and FixedUpdate, and to see how they relate to physics queries.
This example creates a simple Raycast, projecting forwards from the position of the object’s current position, extending for 10 units.
Declaration
Parameters
origin | The starting point of the ray in world coordinates. |
direction | The direction of the ray. |
hitInfo | If true is returned, hitInfo will contain more information about where the closest collider was hit. (See Also: RaycastHit). |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Returns
bool Returns true when the ray intersects any collider, otherwise false.
Description
Casts a ray against all colliders in the Scene and returns detailed information on what was hit.
This example reports the distance between the current object and the reported Collider:
This example re-introduces the maxDistance parameter to limit how far ahead to cast the Ray:
Declaration
Parameters
ray | The starting point and direction of the ray. |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Returns
bool Returns true when the ray intersects any collider, otherwise false.
Description
Declaration
Parameters
ray | The starting point and direction of the ray. |
hitInfo | If true is returned, hitInfo will contain more information about where the closest collider was hit. (See Also: RaycastHit). |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Returns
bool Returns true when the ray intersects any collider, otherwise false.
Description
This example draws a line along the length of the Ray whenever a collision is detected:
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright ©2021 Unity Technologies. Publication Date: 2021-11-26.
Physics2D.Raycast
Успех!
Благодарим вас за то, что вы помогаете нам улучшить качество документации по Unity. Однако, мы не можем принять любой перевод. Мы проверяем каждый предложенный вами вариант перевода и принимаем его только если он соответствует оригиналу.
Ошибка внесения изменений
По определённым причинам предложенный вами перевод не может быть принят. Пожалуйста попробуйте снова через пару минут. И выражаем вам свою благодарность за то, что вы уделяете время, чтобы улучшить документацию по Unity.
Параметры
origin | @param origin Стартовая точка фигуры в 2D пространстве. |
direction | @param direction Вектор, представляющий направление фигуры. |
distance | Maximum distance over which to cast the ray. |
layerMask | @param layerMask Фильтр для обнаружения коллайдеров только на определённых слоях. |
minDepth | @param minDepth Включает только объекты с координатой Z (глубиной) выше, чем это значение. |
maxDepth | @param maxDepth Включает только объекты с координатой Z (глубиной) меньше, чем это значение. |
Возврат значений
RaycastHit2D The cast results returned.
Описание
Casts a ray against colliders in the scene.
BoxCast, концептуально, это как протягивание коробки сквозь сцену в определенном направлении. Любой объект, вступающий в контакт с коробкой, может быть обнаружен и зарегистрирован.
This function returns a RaycastHit object with a reference to the collider that is hit by the ray (the collider property of the result will be NULL if nothing was hit). The layerMask can be used to detect objects selectively only on certain layers (this allows you to apply the detection only to enemy characters, for example).
Raycasts are useful for determining lines of sight, targets hit by gunfire and for many other purposes in gameplay.
Additionally, this will also detect Collider(s) at the start of the ray. In this case the ray is starting inside the Collider and doesn’t intersect the Collider surface. This means that the collision normal cannot be calculated in which case the collision normal returned is set to the inverse of the ray vector being tested. This can easily be detected because such results are always at a RaycastHit2D fraction of zero.
Physics.Raycast
Успех!
Благодарим вас за то, что вы помогаете нам улучшить качество документации по Unity. Однако, мы не можем принять любой перевод. Мы проверяем каждый предложенный вами вариант перевода и принимаем его только если он соответствует оригиналу.
Ошибка внесения изменений
По определённым причинам предложенный вами перевод не может быть принят. Пожалуйста попробуйте снова через пару минут. И выражаем вам свою благодарность за то, что вы уделяете время, чтобы улучшить документацию по Unity.
Параметры
origin | The starting point of the ray in world coordinates. |
direction | @param ray Начальная точка и направление луча. |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore Colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Возврат значений
Описание
You may optionally provide a LayerMask, to filter out any Colliders you aren’t interested in generating collisions with.
Specifying queryTriggerInteraction allows you to control whether or not Trigger colliders generate a hit, or whether to use the global Physics.queriesHitTriggers setting.
This example creates a simple Raycast, projecting forwards from the position of the object’s current position, extending for 10 units.
Notes: Raycasts will not detect Colliders for which the Raycast origin is inside the Collider.
If you move Colliders from scripting or by animation, you need to allow at least one FixedUpdate to be executed so that the physics library can update before a Raycast will hit the Collider at its new position.
Параметры
origin | The starting point of the ray in world coordinates. |
direction | @param ray Начальная точка и направление луча. |
hitInfo | If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit). |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Возврат значений
Описание
Casts a ray against all colliders in the scene and returns detailed information on what was hit.
This example reports the distance between the current object and the reported Collider:
This example re-introduces the maxDistance parameter to limit how far ahead to cast the Ray:
Параметры
ray | @param ray Начальная точка и направление луча. |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Возврат значений
Описание
Параметры
ray | @param ray Начальная точка и направление луча. |
hitInfo | If true is returned, hitInfo will contain more information about where the collider was hit (See Also: RaycastHit). |
maxDistance | The max distance the ray should check for collisions. |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
queryTriggerInteraction | Specifies whether this query should hit Triggers. |
Возврат значений
Описание
This example draws a line along the length of the Ray whenever a collision is detected:
Русские Блоги
Краткое введение в Ray и RaycastHit в Unity
Скобки обращены соответственно к точке излучения луча, направлению луча, максимальному расстоянию луча, пояс обнаружения не имеет коллайдера, и неколлайдер не может поразить другой объект
В документации API приведены только эти методы:
public static bool Raycast(Ray ray, RaycastHit hitInfo, float distance, int layerMask);
public static bool Raycast(Ray ray, float distance, int layerMask);
public static bool Raycast(Vector3 origin, Vector3 direction, float distance, int layerMask);
2. RaycastHit Класс используется для хранения информации о столкновениях, созданной после испускания луча. Обычно используются следующие переменные-члены: коллайдер, в котором коллайдер сталкивается с лучом.
distance Расстояние от начальной точки луча до точки пересечения луча и коллайдера.
normal Нормальный вектор луча, входящего в плоскость.
point Координаты точки пересечения луча и коллайдера (объект Vector3)
Посмотрим, что за чертовщина RaycastHit.
Сначала объявите переменную попадания типа RaycastHit.После метода Physics.Raycast () переменная попадания несет некоторую информацию об объекте, с которым столкнулся луч.
Какую информацию это включает? Как показано на рисунке:
(Для концепций, которых вы не знаете, напишите простой код, чтобы попробовать его самостоятельно, вы получите много пользы!)
Здесь мы используем Hit для получения информации о преобразовании. Можно ли с помощью преобразования куба не управлять его движением?
Луч: В программе его можно понимать как луч, который представляет собой луч из определенного положения (исходной точки) в определенное направление (направление);
луч: информация о структуре луча, включая начальную точку и направление; то есть луч
hitinfo: информация об объекте, пораженном этим лучом;
maxDistance: максимальное расстояние этого луча;