Quaternion unity что это
Rotation and Orientation in Unity
Rotations in 3D applications are usually represented in one of two ways: Quaternions or Euler angles. Each has its own uses and drawbacks. Unity uses Quaternions internally, but shows values of the equivalent Euler angles 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 to make it easy for you to edit.
Euler angles and quaternions
Euler angles
Quaternions
Quaternions can be used to represent the orientation or rotation of a GameObject. This representation internally consists of four numbers (referenced in Unity as x, y, z & w) however these numbers don’t represent angles or axes and you never normally need to access them directly. Unless you are particularly interested in delving into the mathematics of Quaternions, you only really need to know that a Quaternion represents a rotation in 3D space and you never normally need to know or modify the x, y & z properties.
Unity stores all GameObject rotations internally as Quaternions, because the benefits outweigh the limitations.
The Transform Inspector displays the rotation using Euler angles, because this is easier to understand and edit. Unity converts new values into the Inspector for the rotation of a GameObject into a new Quaternion rotation value for the GameObject.
The rotation of a GameObject is displayed and edited as Euler angles in the Inspector, but is stored internally as a Quaternion
As a side-effect, it is possible in the Inspector to enter a value of, say, X: 0, Y: 365, Z: 0 for a GameObject’s rotation. This value is not possible to represent as a quaternion, so when you enter Play mode, the GameObject’s rotation values change to X: 0, Y: 5, Z: 0. This is because Unity converts rotation to a Quaternion which does not have the concept of a full 360-degree rotation plus 5 degrees, and instead is set to orient the same way as the result of the rotation.
To learn more about scripting with the Quaternion class, see the Quaternion User Manual page and the Quaternion Scripting Reference
Implications for Animation
Many 3D authoring packages, and Unity’s own internal Animation window, allow you to use Euler angles to specify rotations during an animation.
These rotations values can frequently exceed ranges expressable by quaternions. For example, if a GameObject rotates 720 degrees, this could be represented by Euler angles X: 0, Y: 720, Z:0. But this is not representable by a Quaternion value.
Unity’s Animation Window
External Animation Sources
When importing animation from external sources, these files usually contain rotational keyframe A frame that marks the start or end point of a transition in an animation. Frames in between the keyframes are called inbetweens.
See in Glossary animation in Euler format. Unity’s default behaviour is to resample these animations and generate a new Quaternion keyframe for every frame in the animation, in an attempt to avoid any situations where the rotation between keyframes may exceed the Quaternion’s valid range.
For example, imagine two keyframes, 6 frames apart, with values for X as 0 on the first keyframe and 270 on the second keyframe. Without resampling, a quaternion interpolation between these two keyframes would rotate 90 degrees in the opposite direction, because that is the shortest way to get from the first orientation to the second orientation. However by resampling and adding a keyframe on every frame, there are now only 45 degrees between keyframes so the rotation works correctly.
Rotation and Orientation in Unity
Summary
Rotations in 3D applications are usually represented in one of two ways, Quaternions or Euler angles. Each has its own uses and drawbacks. Unity uses Quaternions internally, but shows values of the equivalent Euler angles in the inspector to make it easy for you to edit.
The Difference Between Euler Angles and Quaternions
Euler Angles
Euler angles have a simpler representation, that being three angle values for X, Y and Z that are applied sequentially. To apply a Euler rotation to a particular object, each rotation value is applied in turn, as a rotation around its corresponding axis.
Quaternions
Quaternions can be used to represent the orientation or rotation of an object. This representation internally consists of four numbers (referenced in Unity as x, y, z & w) however these numbers don’t represent angles or axes and you never normally need to access them directly. Unless you are particularly interested in delving into the mathematics of Quaternions, you only really need to know that a Quaternion represents a rotation in 3D space and you will never normally need to know or modify the x, y & z properties.
In Unity all Game Object rotations are stored internally as Quaternions, because the benefits outweigh the limitations.
In the Transform Inspector however, we display the rotation using Euler angles, because this is more easily understood and edited. New values entered into the inspector for the rotation of a Game Object are converted “under the hood” into a new Quaternion rotation value for the object.
The rotation of a Game Object is displayed and edited as Euler angles in the inspector, but is stored internally as a Quaternion
As a side-effect, it is possible in the inspector to enter a value of, say, X: 0, Y: 365, Z: 0 for a Game Object’s rotation. This is a value that is not possible to represent as a quaternion, so when you hit Play you’ll see that the object’s rotation values change to X: 0, Y: 5, Z: 0 (or thereabouts). This is because the rotation was converted to a Quaternion which does not have the concept of “A full 360-degree rotation plus 5 degrees”, and instead has simply been set to be oriented in the same way as the result of the rotation.
Implications for Scripting
Creating and Manipulating Quaternions Directly
Unity’s Quaternion class has a number of functions which allow you to create and manipulate rotations without needing to use Euler angles at all. For example:
However sometimes it’s desirable to use Euler angles in your scripts. In this case it’s important to note that you must keep your angles in variables, and only use them to apply them as Euler angles to your rotation. While it’s possible to retrieve Euler angles from a quaternion, if you retrieve, modify and re-apply, problems will arise.
Here are some examples of mistakes commonly made using a hypothetical example of trying to rotate an object around the X axis at 10 degrees per second. This is what you should avoid:
And here is an example of using Euler angles in script correctly:
Implications for Animation
Many 3D authoring packages, and indeed Unity’s own internal animation window, allow you to use Euler angles to specify rotations during an animation.
These rotations values can frequently exceed range expressable by quaternions. For example, if an object should rotate 720 degrees in-place, this could be represented by Euler angles X: 0, Y: 720, Z:0. But this is simply not representable by a Quaternion value.
Unity’s Animation Window
External Animation Sources
When importing animation from external sources, these files usually contain rotational keyframe animation in Euler format. Unity’s default behaviour is to resample these animations and generate a new Quaternion keyframe for every frame in the animation, in an attempt to avoid any situations where the rotation between keyframes may exceed the Quaternion’s valid range.
For example, imagine two keyframes, 6 frames apart, with values for X as 0 on the first keyframe and 270 on the second keyframe. Without resampling, a quaternion interpolation between these two keyframes would rotate 90 degrees in the opposite direction, because that is the shortest way to get from the first orientation to the second orientation. However by resampling and adding a keyframe on every frame, there are now only 45 degrees between keyframes so the rotation will work correctly.
Quaternion
struct in UnityEngine
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.
Description
Quaternions are used to represent rotations.
They are compact, don’t suffer from gimbal lock and can easily be interpolated. Unity internally uses Quaternions to represent all rotations.
They are based on complex numbers and are not easy to understand intuitively. You almost never access or modify individual Quaternion components (x,y,z,w); most often you would just take existing rotations (e.g. from the Transform) and use them to construct new rotations (e.g. to smoothly interpolate between two rotations). The Quaternion functions that you use 99% of the time are: Quaternion.LookRotation, Quaternion.Angle, Quaternion.Euler, Quaternion.Slerp, Quaternion.FromToRotation, and Quaternion.identity. (The other functions are only for exotic uses.)
You can use the Quaternion.operator * to rotate one rotation by another, or to rotate a vector by a rotation.
Note that Unity expects Quaternions to be normalized.
Static Properties
Properties
eulerAngles | Returns or sets the euler angle representation of the rotation. |
normalized | Returns this quaternion with a magnitude of 1 (Read Only). |
this[int] | Access the x, y, z, w components using [0], [1], [2], [3] respectively. |
w | W component of the Quaternion. Do not directly modify quaternions. |
x | X component of the Quaternion. Don’t modify this directly unless you know quaternions inside out. |
y | Y component of the Quaternion. Don’t modify this directly unless you know quaternions inside out. |
z | Z component of the Quaternion. Don’t modify this directly unless you know quaternions inside out. |
Constructors
Public Methods
Set | Set x, y, z and w components of an existing Quaternion. |
SetFromToRotation | Creates a rotation which rotates from fromDirection to toDirection. |
SetLookRotation | Creates a rotation with the specified forward and upwards directions. |
ToAngleAxis | Converts a rotation to angle-axis representation (angles in degrees). |
ToString | Returns a formatted string of the Quaternion. |
Static Methods
Angle | Returns the angle in degrees between two rotations a and b. |
AngleAxis | Creates a rotation which rotates angle degrees around axis. |
Dot | The dot product between two rotations. |
Euler | Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis; applied in that order. |
FromToRotation | Creates a rotation which rotates from fromDirection to toDirection. |
Inverse | Returns the Inverse of rotation. |
Lerp | Interpolates between a and b by t and normalizes the result afterwards. The parameter t is clamped to the range [0, 1]. |
LerpUnclamped | Interpolates between a and b by t and normalizes the result afterwards. The parameter t is not clamped. |
LookRotation | Creates a rotation with the specified forward and upwards directions. |
Normalize | Converts this quaternion to one with the same orientation but with a magnitude of 1. |
RotateTowards | Rotates a rotation from towards to. |
Slerp | Spherically interpolates between quaternions a and b by ratio t. The parameter t is clamped to the range [0, 1]. |
SlerpUnclamped | Spherically interpolates between a and b by t. The parameter t is not clamped. |
Operators
operator * | Combines rotations lhs and rhs. |
operator == | Are two quaternions equal to each other? |
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-20.
Quaternion unity что это
Кватернионы используются для представления вращений.
В Unity все вращения представлены в виде кватернионов. Их использование решает проблему «шарнирного замка» (gimbal lock).
Вникать во внутреннее устройство кватернионов нам нет нужды, мы можем просто их использовать 🙂
И для начала разберемся как получить кватернион из привычных векторов и углов.
Первый способ (углы указываются в градусах):
Второй способ (значения вращения по каждой оси в градусах):
И в случае с методом и в случае со свойством вращение применяется в порядке: Z, X, Y. Стоит это учитывать, чтобы не было неожиданных поворотов
Третий способ (через ось и угл вращения вокруг неё в градусах):
Получить углы Эйлера из кватерниона можно через свойство eulerAngles:
Или можно получить ось и угол вращения вокруг нее:
Теперь разберемся, как с их помощью вращать объекты.
Для этого нужно кватернион, из которого мы хотим повернуть (текущее положение), умножить на кватернион, на который хотим повернуть.
Пример:
Интерполяция
Данный метод возвращает промежуточное вращение между a и b на основе t. При этом значение t ограничивается диапазоном от 0 до 1.
Вернёт a, при t равное или меньше 0.
Вернёт b, при t равное или больше 1.
От предыдущего он отличается только отсутствием ограничений t. Т.е результат выходит за пределы a и b, если t 1.
Картинка для наглядности:
Имеется прожектор, который нужно вращать по кругу, чтобы освещать всю территорию вокруг него.
Используем для решения сей задачи LerpUnclamped: В данном случае прожектор пройдёт полный круг за 4 сек.
Немного изменим задачу.
Прожектор должен освещать не всё вокруг, а только сектор в 90 градусов.
Для этого заменим LerpUnclamped на Lerp. А чтобы прожектор не стопорился в конце, обвернём значение времени функцией Mathf.PingPong:
Задаём направления
Функция FromToRotation (или ее аналог SetFromToRotation) создает такой кватернион, что если его применить к fromDirection, то направление этого вектора совпадёт с toDirection: Обычно используется, чтобы повернуть объект так, чтобы одна из его осей смотрела в нужном направлении.
Функция LookRotation (или SetLookRotation) создает вращение, при котором ось Z сонаправленна forward, а ось Y сонаправленна upwards.
Можно использовать, например, чтобы поворачивать персонажа к целе:
Добавим интерполяцию и регулятор скорости для плавности: На этом всё 🙂
Русские Блоги
Подробное объяснение кватернионных классов в Unity [подробно]
I. Введение
Кватернион, также известный как кватернион, состоит из четырех компонентов x, y, z и w. Это математическая концепция, открытая ирландским математиком Уильямом Лоуэном Гамильтоном в 1843 году. Умножение кватернионов не соответствует коммутативному закону. С четкой точки зрения кватернионы являются необратимым продолжением множественного числа. Если множество кватернионов рассматривается как многомерное пространство действительных чисел, кватернион представляет собой четырехмерное пространство, а не двумерное пространство для комплексных чисел.
кватернион
Для ознакомления со свойствами кватернионов, их связи с вращением и сферической линейной интерполяцией, пожалуйста, прочитайтеМатематические методы в 3D играх и компьютерной графике-кватернионахНет больше введения здесь. Следующее в основном вводит Quaternion в Unity.
В Unity Quaternion используется для хранения и представления угла поворота объекта. Преобразование кватерниона более сложное: для общего поворота и перемещения GameObject вы можете использовать соответствующие методы в Transform для реализации.
Во-вторых, атрибуты класса Quaternion
eulerAngles- Эйлера углы
Ниже приведен пример, демонстрирующий использование углов Эйлера.
В-третьих, метод экземпляра класса Quaternion
Вы можете создать экземпляр Quaternion от formDirection до toDirection.
Объект GameObject можно преобразовать следующим образом. Сначала направления осей x, y и z собственной системы координат объекта GameObject соответствуют направлениям осей x, y и z мировой системы координат, а затем направление, в котором вектор V1 собственной системы координат объекта GameObject указывает. Поверните к V2.
1.2 PS: Вы не можете напрямую использовать transform.rotation.SetFromToRotation (v1, v2) для установки. Вы можете только скопировать экземпляр Quaternion в transform.rotation.
Результаты показаны на следующем рисунке:
SetLookRotation метод-Установить ориентацию экземпляра Quaternion
Направление transform.forward совпадает с направлением V1.
transform.right перпендикулярен плоскости, состоящей из трех точек Vector3.zer0, V1 и V2.
V2 определяет направление transform.up, потому что после определения направлений transform.forward и transform.right угол между направлением transform.up и направлением V2 всегда меньше или равен 90 градусам.
2.2 PS: Как и выше, не используйте transform.rotation.SetLookRotation (v1, v2) для создания объектов Quaternion.
2.3 Примеры
Метод 3.ToAngleAxis
Угол параметра является углом поворота, а ось параметра является вектором оси.
Эта функция может преобразовать вращение объекта GameObject из состояния Quaternion.identity в текущее состояние. Вам нужно только повернуть объект GameObject вокруг оси (мировой системы координат) на угол.
3.2 Пример демонстрации
В-четвертых, статические методы класса Quaternion
В Quaternion есть девять статических методов: метод угла, метод точки, метод Эйлера, метод FromToRotation, метод Inverse, метод Lerp, метод LookRotation, метод RotateToWards и метод Slerp. Использование статических методов состоит в том, чтобы вызывать их статические методы напрямую с именем класса, например Quaternion.Angle (q1, q2), а также последующий анализ этих статических методов.
1. Угловой метод
Этот метод может вычислить минимальный включенный угол между двумя состояниями вращения от a до b.
1.2 Пример демонстрации
Из выходных данных видно, что значения a1 и a2 равны, то есть возвращаемое значение Angle является минимальным углом между двумя экземплярами Quaternion.
2. Точечный метод умножения точек
Этот метод может оценить соотношение между a и b, соответствующее углу Эйлера, в соответствии с результатом умножения точки.
Например, если есть два кватернионных экземпляра q1 (x1, y1, z1, w1) и q2 (x2, y2, z2, w2), то float f = Quaternion.Dot (q1, q2), то есть f = x1 * x2 + y1 * y2 + z1 * z2 + w1 * w2, диапазон значения результата f равен [-1,1].
2.2 Пример демонстрации
3. Метод Эйлера
Этот метод используется для возврата кватерниона Quaternion q (qx, qy, qz, qw), соответствующего углу Эйлера Vector3 (ex, ey, ez). Соответствующее соотношение выглядит следующим образом:
Известно, что PIover180 = 3.141592 / 180 = 0.0174532925f является постоянным источником света в компьютерной графике, и процесс его преобразования заключается в следующем:
3.2 Проверьте процесс преобразования
Вывод может доказать, что формула верна, кроме того, если преобразованный кватернион выводится напрямую, он выглядит следующим образом:
Выходное значение округляется.
Метод 4.FromToRotation
Метод экземпляра SetFromToRotation был представлен ранее, их функции одинаковы, но использование немного отличается. Чтобы использовать статический метод класса FromToRotation, необходимо вызвать его напрямую с именем класса, например Quaternion.FromToRotation (v1, v2);
Не делай демо здесь!
5. Обратный метод
5.1 Функциональный прототип
Этот метод может вернуть значение обратного кватерниона параметра поворота.
6.Lerp и Slerp методы
6.1 Функциональный прототип
7.RotateTowards метод
7.1 Функциональный прототип
Интеллектуальная рекомендация
Gensim Skip-Gram модель для Word2Vec
Встраиваем VSCode в OpenCV IDE (C ++, window10 1803)
Каталог статей вступление окружение шаг 1. Конфигурация Visual Studio Code 2. Конфигурация OpenCV 3. Конфигурация MinGw 4. Конфигурация cmake 5. Конфигурация проекта 6. Ссылка на ссылку В конце концов.
Интеграция и инструменты fastDFS + spring + maven
Основы Linux
Пользователи Linux делятся на два типа: Пользователь суперадминистратора: root, хранится в каталоге / root Обычные пользователи: хранятся в каталоге / home Каталог Linux /: [*] Корневой каталог. Как п.