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

Quaternion unity что это

  • автор:

Unity Quaternion and Rotation Guide for beginners

Unity Quaternion may sound complex but it’s just another datatype like Vector3 that hold the rotation data of a Gameobject. In this tutorial, we are going to see how to use Quaternion effectively to perform rotations in Unity and how to rotate an object without Quaternion.

Unity quaternion blog post banner

What is a Quaternion in Unity?

Quaternion is a combination of a vector3 and a scalar used to represent the rotation or orientation of an object.

The structure of quaternion looks like this (xi, yj,zk,w) where (xi,yj,zk) is a unit vector that represents the angle between the orientation and each individual axis. “w” represents the degree of rotation along the unit vector (xi,yj,zk).

In Unity, Quaternion can also be represented using a vector 4.

Quaternion vs Euler angles in Unity

The easier way to represent a rotation is using Euler Angles. A rotation in Euler Angles is basically the degree in each Axis (45,0,45).

There are certain limitations to Euler angles.

  1. Euler angles are subjected to Gimbal lock. It happens when two Axis align with each other and we lose one degree of freedom. Quaternion overcomes this limitation.
  2. In order to rotate a 3D object, you require a rotation matrix that increases the computational requirement. Quaternion represents rotation in just 4 numbers and is easy to be processed.

Unity allows you to specify Euler angles and save them to Quaternion. It’s discussed in the later part of this blog post.

Quaternion Example

Here is how Unity Displays Quaternion and Euler Angles for a Cube that has a rotation of (0,0,0)

Unity quaternion vs Euler example 1 Unity quaternion vs Euler example 2

Creating a new Quaternion

Quaternion is a Unity C# class. So, to create a new Quaternion, you need to create an object of the class and the syntax is shown below.

To set the value you can either give it while creating the new Quaternion like this

or you can use “Quaternion dot Set”

What is Quaternion.Identity?

Quaternion identity refers to zero rotation in all axis. Quaternion identity is frequently used for instantiating an object with zero rotation in Unity.

Quaternion.identity is equal to setting a quaternion value of (0,0,0,1) to a game object.

Different ways to rotate in Unity

Like movement in Unity there are multiple ways to rotate in Unity. You can rotate an object using transform or you can create a simple animation or you can use Physics.

In this tutorial we will see how to rotate an object using Physics, Quaternion and Euler angles.

Transform Rotation vs Transform Rotate

transform.rotation takes a Quaternion and transform.rotate take a Vector3 with Euler angles.

“transform.rotate” add the rotation to already existing values, whereas transform.rotation assigns the Quaternion value directly to the object.

The difference is very similar to using transform.position and transform.translate.

Transform Rotation syntax

Transform rotate syntax

Rotating an object using Euler Angles

This is the most used method when you have to provide the rotation value manually.

Use a Vector3 to store the values of by which you want the object to rotate in each Axis and then pass them to “transform.rotate”.

Here is a code sample to rotate the object by 10 degrees in each axis

Rotating an object using Unity Quaternion

It’s really difficult to know the quaternion value for rotation unless you are very familiar with the concept. But if you do know the value then you can create a new Quaternion and assign it to rotation of the object.

Remember none of the parameters of a Quaternion should be greater than 1. The values should be between (-1 to 1).

Here is a sample code

The Above code will directly assign the rotation data to the Gameobject.

Rotating an Object using Physics

It’s very important to use Physics forces on Rigid body to rotate or it might break. To rotate an object, we need to use the rotation equivalent of force. It’s called Torque. The syntax to apply Torque in Unity is very similar to applying force.

Here is a sample code to apply an impulse Torque.

Converting Vector3 to Quaternion

As mentioned earlier knowing the exact value of Quaternion is difficult for non-mathematicians. Unity provides a way to convert Euler angles saved as Vector3 to Quaternion.

Here is a simple example of how to assign a Vector3 to quaternion as Euler Angles.

Convert Quaternion to Vector3

Similar to the above example you can also convert a Quaternion to Vector3. Any conversion between Quaternion and Vector3 includes Euler Angles.

You can extract the Euler angles from the quaternion and set them to a Vector3.

Here is a sample code

Rotate by one Degree Every Frame

Now that you are clear with the concept of Unity Quaternion and Euler angles let’s see some examples. Let’s try to rotate an object by 1 degree every frame.

First you need a vector 3 with all three Axis values as 1.

We will use the Vector 3 as Euler angles and rotate the game object. Here is the code we are going to use

Here is the out of the above code

You can also use Quaternion Lerp to slowly rotate an object over time.

Rotate an Object around a point

This is very useful for creating camera effects or Planetary motions.

You can rotate an object on its own axis using transform rotate but if you want to rotate an object around a different point and along a custom axis then this is for you.

We have two objects, a cube and a sphere, in our scene. Let’s rotate the cube around the sphere for the purpose of this tutorial.

We will be using “transform.rotateAround” for this purpose. It takes in 3 arguments.

The first one is a vector3 point in space around which you want the object to rotate. The second argument is the axis and the third one is the angular speed.

Let’s add the script below to our cube object. Make sure the sphere and the cube are not in the same position.

Select the cube and go to the Inspector window.

Click on add component and select new script.

Name the script as move_around

Copy and paste the code below into the script.

Here is the output

If you change the axis from Vector3.up to Vector3.forward

The cube starts rotating around a different axis

Rotating a 2D object in Unity

You can rotate a 2D object similar to a 3D object. You should only be sure of which axis you want to rotate the object in.

The default Unity 2D movement is along the X and Y axis. So, to rotate an 2D object you must change the rotation in Z axis.

You can use the above code with the Euler angles set to zero for X and Y. Here is an example

Here is the output for the above code

How to reset rotation in Unity

Every now and then during gameplay we tend to rotate the camera to an angle where it is no longer useful. At that time, we reset the camera view to start from the beginning.

Unity has a inbuild function to reset rotation. It’s a part of Quaternion. You just have to set the rotation to “Quaternion. Identity”. This will reset the rotation to (0,0,0).

Here is a sample code.

You can assign the function to a UI button to reset the rotation when the player wants.

Quaternion

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 <a>try again</a> 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.

Важные классы — Quaternion

Unity использует Quaternion стандартный способ Unity для представления поворотов в виде данных. При написании кода, имеющего дело с поворотами, обычно следует использовать класс Quaternion и его методы. Подробнее
См. в классе Словарь для хранения трехмерной ориентации GameObjects Основной объект в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки и многое другое. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь , а также использовать их для описания относительного поворота от одного ориентация на другого.

На этой странице представлен обзор класса Quaternion и его частого использования при написании сценариев с его помощью. Исчерпывающую информацию о каждом члене класса Quaternion см. в справочнике по скрипту Quaternion.

Важно понимать разницу между углами Эйлера (значениями X, Y и Z, которые вы видите в инспекторе для поворота GameObject) и базовым значением Quaternion, которое Unity использует для хранения фактического поворота GameObjects. Основы этой темы см. в статье Вращение и ориентация в Unity.

При работе с поворотами в ваших скриптах фрагмент кода, который позволяет создавать собственные компоненты, запускающие игровые события , изменяйте свойства компонента с течением времени и реагируйте на ввод данных пользователем любым удобным для вас способом. Подробнее
См. в Словарь , вы должны использовать класс Quaternion и его функции для создания и изменить значения вращения. В некоторых ситуациях допустимо использование углов Эйлера, но вы должны помнить:
– Вам следует использовать функции класса Quaternion, которые имеют дело с углами Эйлера
— Получение, изменение и повторное применение значений Эйлера из поворота может привести к непреднамеренным побочным эффектам (см. ниже)

Непосредственное создание кватернионов и управление ими

Класс Quaternion в Unity имеет ряд функций, которые позволяют создавать повороты и управлять ими без использования углов Эйлера, и именно эти функции следует использовать в большинстве типичных случаев. Каждая из этих ссылок на Справочник по сценариям с примерами кода:

Создание поворотов:

Управление поворотами:

Класс Transform также предоставляет методы, позволяющие работать с поворотами кватерниона:

Работа с углами Эйлера

В некоторых случаях предпочтительнее использовать в сценариях углы Эйлера. При этом важно помнить, что вы должны хранить свои углы в переменных и использовать их только для применения их в качестве углов Эйлера к вашему повороту, который в конечном итоге все равно должен храниться как кватернион. Хотя можно получить углы Эйлера из кватерниона, при извлечении, изменении и повторном применении могут возникнуть проблемы.

Подробнее о том, как именно могут возникнуть эти проблемы, можно прочитать на справочной странице скриптов eulerAngles.

Вот несколько примеров ошибок, которые обычно делаются на гипотетическом примере попытки повернуть игровой объект вокруг оси X со скоростью 10 градусов в секунду. Вот чего следует избегать:

// rotation scripting mistake #1 // the mistake here is that we are modifying the x value of a quaternion // this value does not represent an angle, and does not produce desired results void Update () < var rot = transform.rotation; rot.x += Time.deltaTime * 10; transform.rotation = rot; >// rotation scripting mistake #2 // Read, modify, then write the Euler values from a Quaternion. // Because these values are calculated from a Quaternion, // each new rotation might return very different Euler angles, which might suffer from gimbal lock. void Update ()

А вот пример использования углов Эйлера в скрипте правильно:

// Rotation scripting with Euler angles correctly. // Store the Euler angle in a class variable, and only use it to // apply it as an Euler angle, but never rely on reading the Euler back. float x; void Update ()

How can We Use Quaternion in Unity?

Quaternions are an extension of complex numbers and can be used to represent 3D rotations, spatial translations, and scaling. Invented by Sir William Rowan Hamilton in 1843, these numbers are not easy to understand intuitively. With all honesty, I still don't fully know how it works.

However, in Unity, we can handle the rotation without having to understand them fully. Now, Let’s look at some useful things we can do with Unity Quaternion API

1. Slerp

public static Quaternion Slerp(Quaternion a, Quaternion b, float t);

Slerp is a spherical interpolation between quaternions a and b by the ratio of t . The parameter t is clamped in between [0, 1].

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

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