Web server is returning an unknown error Error code 520
There is an unknown connection issue between Cloudflare and the origin web server. As a result, the web page can not be displayed.
What can I do?
If you are a visitor of this website:
Please try again in a few minutes.
If you are the owner of this website:
There is an issue between Cloudflare’s cache and your origin web server. Cloudflare monitors for these errors and automatically investigates the cause. To help support the investigation, you can pull the corresponding error log from your web server and submit it our support team. Please include the Ray ID (which is at the bottom of this error page). Additional troubleshooting resources.
Cloudflare Ray ID: 7a69f262406d2d7f • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Unity Fundamentals — Rotate a game object in movement’s direction
Rotations can be confusing. Understand them, and learn how to rotate the game object in the direction of a movement in this simple tutorial.
Resources
What we want to achieve
Move a game object
First, start with the movement functionality.
I have a blog post and video about the movement, so I will not into big details here. We want to focus on rotation.
Rotation Part
Let’s start with targetRotation. Rotations are usually stored as a Quaternion type. You can store them as Vector3, but you will see Quaternions more often.
Quaternions are based on complex numbers and consist of 4 components (x,y,z,w). They are not very intuitive to understand. That’s not a big problem because you never(rarely) need to modify them.
What you need to know is that they are used for rotations.
However, if you would like to understand them, there is a lot of resources that can help you out:
Let’s talk more about targetRotation
To LookRotation, we are providing movement Vector3. Movement is holding the value of the player input.
If Movement has value (1,0,0), the object is moving right, if (0,0,1) it’s moving forward, etc.
The official description of LookRotation is:
Creates a rotation with the specified forward and upwards directions.
LookRotation is expecting to receive 2 values, forward vector and upwards vector.
We are providing forward. It’s our movement vector.
We can also specify an upwards vector. In this case, it’s not needed because the default value of the upwards vector is Vector3.up which is (0,1,0).
This is how the vector forwards and upwards vector looks relatively to our game object.
Vector3.forward is (0,0,1) and Vector3.up is (0,1,0)
Let’s imagine the case player wants to move, so it’s facing right. In that case, the movement vector will be (1,0,0)
Now let’s ask the question: How many degrees have to game object rotates on Y-axis, so Vector3.forward aligns with movement (1,0,0) .
The answer is: We need to rotate Y exactly 90 degrees.
This is how it looks in the game.
That’s basically the entire rotation functionality we wanted to implement.
You can notice the transition of the rotation is happening too fast, almost immediately. Let’s smooth it out.
Rotate towards
We are going to re-assign targetRotation with the result of RotateTowards method.
The formal description of this method is:
Rotates a rotation from towards to.
To this method, we need to provide 3 values,
- Rotation in which we are currently in, that’s transform.rotation
- Rotation we want transit to, that’s targetRotation
- max amount of degrees we can rotate. We are specifying we can rotate a maximum of 360 degrees in one second. Hence 360 * Time.fixedDeltaTime
This will smooth out the rotation. You can try it out.
Recap
You have just learned how easily you can rotate a game object in the direction of the movement.
Transform.Rotate
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
Use Transform.Rotate to rotate GameObjects in a variety of ways. The rotation is often provided as an Euler angle and not a Quaternion.
You can specify a rotation in world axes or local axes.
World axis rotation uses the coordinate system of the Scene , so when you start rotate a GameObject, its x, y, and z axes are aligned with the x, y, and z world axes. So if you rotate a cube in world space, its axes align with the world. When you select a cube in the Unity Editor’s Scene view, rotation Gizmos appear for the left/right, up/down and forward/back rotation axes. Moving these Gizmos rotates the cube around the axes. If you de-select and then re-select the cube, the axes restart in world alignment.
Local rotation uses the coordinate system of the GameObject itself. So, a newly created cube uses its x, y, and z axis set to zero rotation. Rotating the cube updates the rotation axes. If you de-select and the re-select the cube, the axes are shown in the same orientation as before.
A cube not rotated in Local Gizmo Toggle
A cube rotated in Local Gizmo Toggle
A cube not rotated in Global Gizmo Toggle
A cube rotated in Global Gizmo Toggle
For more information on Rotation in Unity, see Rotation and Orientation in Unity.
Поворот и вращение объектов в Unity

Каждый разработчик игр знает, что без вращения и поворотов игровых объектов невозможно сделать нормальную игру. И перед тем, как начать разбор поворота/вращения объекта, создадим игровой объект, и назовём его Player. Его мы и будем вращать.
Как поворот объекта, так и вращение, осуществляется путём изменения значений компонента Transform, и его свойства Transform.rotation.

И начнём данную статью с вращения, так как он более прост и понятен.
Вращение игрового объекта
Для начала разберём, что означает вращение? Вращение, это плавное изменение значений Transform.rotation, вокруг определённых осей. Вот их нам и нужно менять.
Для изменения этих значений, нам поможет метод Transform.Rotate. Работает он следующим образом:
Этот скрипт будет вращать вашего персонажа по оси Z со скоростью 1. Вы так же можете выбрать другую ось вращения, например X или Y. Или же увеличить скорость вращения на 2.
На этом всё! Как видите, вращать игровые объекты очень просто. Теперь перейдём к повороту, который по своей сути немного тяжелее.
Поворот игрового объекта
Поворот персонажа подразумевает его поворот на 180 градусов по одной из осей. Например, очень часто такое может понадобиться в 2д играх, преимущественно платформерного типа. Поэтому в качестве примера мы будем использовать 2д персонажа, которого нужно развернуть по горизонтали, то-есть по оси X.
Предыдущий код вращения нам не поможет, поскольку там мы вращали с помощью специального метода, который прибавляет к старым значениям — новые. Здесь же нам необходимо устанавливать конкретные значения.
Для того, чтобы это сделать, необходимо прописать следующий код:
Давайте разберём код:
- В первой строке с помощью метода Transform.eulerAngles мы получаем значения roration в виде углов эйлера.
- Во второй строке установили значение y в 180, тем самым развернули объект на 180 градусов.
- В третьей строке, элеровские значения конвертируем в кватернионы, и сохраняем полученные данные.
Таким же образом мы можем вернуть объект в нормальное положение:
Аналогичным образом мы можем разворачивать наш объект по любой оси, изменив rotate.y на rotate.x или на rotate.z.
Если остались вопросы, пишите в комментариях. А так же ставьте лайки, если помог 🙂