что такое vector3 в unity

Vectors are a fundamental mathematical concept which allow you to describe a direction and magnitude. In games and apps, vectors are often used to describe some of the fundamental properties such as the position of a character, the speed something is moving, or the distance between two objects.

Vector arithmetic is fundamental to many aspects of computer programming such as graphics, physics and animation, and it is useful to understand it in depth to get the most out of Unity.

Vectors can be expressed in multiple dimensions, and Unity provides the Vector2, Vector3 and Vector4 classes for working with 2D, 3D, and 4D vectors. These three types of Vector classes all share many of the same functions, such as magnitude, so most of the information on this page applies to all three types of Vector unless otherwise specified.

This page provides an overview of the Vector classes and their common uses when scripting with them. For an exhaustive reference of every member of the vector classes, see the script reference pages for Vector2, Vector3 and Vector4.

Understanding Vector Arithmetic

Addition

When two vectors are added together, the result is equivalent to taking the original vectors as “steps”, one after the other. Note that the order of the two parameters doesn’t matter, since the result is the same either way.

что такое vector3 в unity. VectorAdd. что такое vector3 в unity фото. что такое vector3 в unity-VectorAdd. картинка что такое vector3 в unity. картинка VectorAdd.

If the first vector is taken as a point in space then the second can be interpreted as an offset or “jump” from that position. For example, to find a point 5 units above a location on the ground, you could use the following calculation:-

If the vectors represent forces then it is more intuitive to think of them in terms of their direction and magnitude (the magnitude indicates the size of the force). Adding two force vectors results in a new vector equivalent to the combination of the forces. This concept is often useful when applying forces with several separate components acting at once (eg, a rocket being propelled forward may also be affected by a crosswind).

Although the examples here show 2D vectors, the same concept applies to 3D and 4D vectors.

Subtraction

Vector subtraction is most often used to get the direction and distance from one object to another. Note that the order of the two parameters does matter with subtraction:-

что такое vector3 в unity. VectorSubtract. что такое vector3 в unity фото. что такое vector3 в unity-VectorSubtract. картинка что такое vector3 в unity. картинка VectorSubtract.

As with numbers, adding the negative of a vector is the same as subtracting the positive.

The negative of a vector has the same magnitude as the original and points along the same line but in the exact opposite direction.

Direction and Distance from One Object to Another

If one point in space is subtracted from another, then the result is a vector that “points” from one object to the other:

As well as pointing in the direction of the target object, this vector’s magnitude is equal to the distance between the two positions. You may need a “normalized” vector giving the direction to the target, but with a fixed distance (say for directing a projectile). You can normalize a vector by dividing it by its own magnitude:

This approach is preferable to using both the magnitude and normalized properties separately, since they are both quite CPU-hungry (they both involve calculating a square root).

If you only need to use the distance for comparison (for a proximity check, say) then you can avoid the magnitude calculation altogether. The sqrMagnitude property gives the square of the magnitude value, and is calculated like the magnitude but without the time-consuming square root operation. Rather than compare the magnitude against a known distance, you can compare the squared magnitude against the squared distance:-

This is much more efficient than using the true magnitude in the comparison.

Sometimes, when working in 3D, you might need an “overground heading” to a target. For example, imagine a player standing on the ground who needs to approach a target floating in the air. If you subtract the player’s position from the target’s then the resulting vector will point upwards towards the target. This is not suitable for orienting the player’s transform since they will also point upwards; what is really needed is a vector from the player’s position to the position on the ground directly below the target. You can obtain this by taking the result of the subtraction and setting the Y coordinate to zero:-

Scalar Multiplication and Division

When discussing vectors, it is common to refer to an ordinary number (eg, a float value) as a scalar. The meaning of this is that a scalar only has “scale” or magnitude whereas a vector has both magnitude and direction.

Multiplying a vector by a scalar results in a vector that points in the same direction as the original. However, the new vector’s magnitude is equal to the original magnitude multiplied by the scalar value.

Likewise, scalar division divides the original vector’s magnitude by the scalar.

These operations are useful when the vector represents a movement offset or a force. They allow you to change the magnitude of the vector without affecting its direction.

When any vector is divided by its own magnitude, the result is a vector with a magnitude of 1, which is known as a normalized vector. If a normalized vector is multiplied by a scalar then the magnitude of the result will be equal to that scalar value. This is useful when the direction of a force is constant but the strength is controllable (eg, the force from a car’s wheel always pushes forwards but the power is controlled by the driver).

Dot Product

что такое vector3 в unity. DotProduct. что такое vector3 в unity фото. что такое vector3 в unity-DotProduct. картинка что такое vector3 в unity. картинка DotProduct.

Below you can see a comparison of how vectors of varying angles compared with a reference vector return a dot product value between 1 and –1 :

что такое vector3 в unity. CosineValues. что такое vector3 в unity фото. что такое vector3 в unity-CosineValues. картинка что такое vector3 в unity. картинка CosineValues.

The dot product is a mathematically simpler operation than calculating the cosine, so it can be used in place of the Mathf.Cos function or the vector magnitude operation in some circumstances (it doesn’t do exactly the same thing but sometimes the effect is equivalent). However, calculating the dot product function takes much less CPU time and so it can be a valuable optimization.

The dot product is useful if you want to calculate the amount of one vector’s magnitude that lies in the direction of another vector.

Naturally, the direction can be anything you like but the direction vector must always be normalized for this calculation. Not only is the result more correct than the magnitude of the velocity, it also avoids the slow square root operation involved in finding the magnitude.

Cross Product

The cross product is only meaningful for 3D vectors. It takes two 3D vectors as input and returns another 3D vector as its result.

The result vector is perpendicular to the two input vectors. You can use the “right hand screw rule” to remember the direction of the output vector from the ordering of the input vectors. If you can curl your fingers in the order of the input vectors, your thumb points in the direction of the output vector. If the order of the parameters is reversed then the resulting vector will point in the exact opposite direction but will have the same magnitude.

The magnitude of the result is equal to the magnitudes of the input vectors multiplied together and then that value multiplied by the sine of the angle between them. Some useful values of the sine function are shown below:-

что такое vector3 в unity. SineValues. что такое vector3 в unity фото. что такое vector3 в unity-SineValues. картинка что такое vector3 в unity. картинка SineValues.

The cross product can seem complicated since it combines several useful pieces of information in its return value. However, like the dot product, it is very efficient mathematically and can be used to optimize code that would otherwise depend on slower transcendental functions such as sine and cosine.

Computing a Normal/Perpendicular vector

что такое vector3 в unity. CalculateNormal. что такое vector3 в unity фото. что такое vector3 в unity-CalculateNormal. картинка что такое vector3 в unity. картинка CalculateNormal. что такое vector3 в unity. LeftHandRuleDiagram. что такое vector3 в unity фото. что такое vector3 в unity-LeftHandRuleDiagram. картинка что такое vector3 в unity. картинка LeftHandRuleDiagram.

The “left hand rule” can be used to decide the order in which the two vectors should be passed to the cross product function. As you look down at the top side of the surface (from which the normal will point outwards) the first vector should sweep around clockwise to the second:

The result will point in exactly the opposite direction if the order of the input vectors is reversed.

For meshes, the normal vector must also be normalized. This can be done with the normalized property, but there is another trick which is occasionally useful. You can also normalize the perpendicular vector by dividing it by its magnitude:-

Another useful note is that the area of the triangle is equal to perpLength / 2. This is useful if you need to find the surface area of the whole mesh or want to choose triangles randomly with probability based on their relative areas.

Источник

Unity Vectors – What Every Game Developer Needs To Know About Vectors In Unity

Help Others Learn Game Development

As soon as you start with Unity game development you will be bombarded with vectors. Most of the time you will use Vector2 for 2D games and Vector3 for 3D games.

So what are vectors and how can we use them?

Definition Of A Vector

Vectors are a fundamental mathematical concept which allows you to describe a direction and magnitude.

In math, a vector is pictured as a directed line segment, whose length is the magnitude of the vector and the arrow is indicating the direction where the vector is going:

что такое vector3 в unity. Img 1 20. что такое vector3 в unity фото. что такое vector3 в unity-Img 1 20. картинка что такое vector3 в unity. картинка Img 1 20.

Vector2 And Vector3 In Unity

что такое vector3 в unity. Img 2 24. что такое vector3 в unity фото. что такое vector3 в unity-Img 2 24. картинка что такое vector3 в unity. картинка Img 2 24.

что такое vector3 в unity. Img 3 21. что такое vector3 в unity фото. что такое vector3 в unity-Img 3 21. картинка что такое vector3 в unity. картинка Img 3 21.

The values for the axis are located in the Position property of the Transform component of course:

что такое vector3 в unity. Img 4 21. что такое vector3 в unity фото. что такое vector3 в unity-Img 4 21. картинка что такое vector3 в unity. картинка Img 4 21.

The Magnitude Of The Vector

One of the things we use vectors for is to know the magnitude of the game object.

But what is magnitude of a vector?

The magnitude is the distance between the vectors origin (0, 0, 0) and its end point. If we imagine a vector as a straight line, the magnitude is equal to its length as we saw in the first image:

что такое vector3 в unity. Img 1 20. что такое vector3 в unity фото. что такое vector3 в unity-Img 1 20. картинка что такое vector3 в unity. картинка Img 1 20.

To calculate the magnitude in math, given a position vector → v = ⟨a,b⟩, the magnitude is found by magnitude = √a2 + b2 (square root of a squared + b squared).

In 3D it works the same way, except that we have one more axis in the calculation magnitude = √a2 + b2 + z2 (square root of a squared + b squared + z squared).

But in Unity we simply do this:

что такое vector3 в unity. Img 5 20. что такое vector3 в unity фото. что такое vector3 в unity-Img 5 20. картинка что такое vector3 в unity. картинка Img 5 20.

For What Do We Use The Magnitude Of A Vector

The magnitude of a vector is used to measure the speed of the vector. I say speed of the vector but its actually the speed of the game object.

For example, if we are moving the game object using its Transform component, we can limit the movement speed using the magnitude of the vector:

Squared Magnitude

One thing that we need to be careful here is that this will calculate the magnitude without using the square root in the operation, which means it will return the magnitude squared e.g. the magnitude will 2x of its actual value.

So if we want to compare a distance between two vectors or the speed of the current vector we need to compare the squared values:

The Direction Of The Vector

One of the most common informations we need in a game is the direction of vectors which indicates in which direction a specific game object is going. This is used to move characters in the game, to create enemy AI and so on.

To get the direction of the vector we need to normalize it, and in Unity we normalize a vector like this:

Using normalized or Normalize will give us the direction of the given vector.

Now you are probably asking what is the difference between the two?

Both lines of code will normalize(return the direction) the given vector, but using normalized on a vector will return a new version of the same vector that we can store in a new variable, and the original version of the vector will stay the same.

Using the Normalize function however, will normalize the vector is self e.g. it will change the original vector.

If you hover over the normalized word in the code you will see the following explanation:

что такое vector3 в unity. Img 6 20. что такое vector3 в unity фото. что такое vector3 в unity-Img 6 20. картинка что такое vector3 в unity. картинка Img 6 20.

This means that the returned vector has a magnitude of 1 e.g. the length of that vector is 1, because this is how directions are represented in Unity.

что такое vector3 в unity. Img 7 22. что такое vector3 в unity фото. что такое vector3 в unity-Img 7 22. картинка что такое vector3 в unity. картинка Img 7 22.

As you can see, X is positive on right side and negative on the left, Y is positive up and negative down, and Z is positive forward and negative backwards.

This is why you see the positive 1 and negative 1 values for the vectors in the code example above.

What Is The Difference Between Vector Magnitude And Vector Normalize

From all the examples we saw so far for the vector’s magnitude and normalization, we can conclude that there is a difference between them and they are both used for different purposes.

The magnitude returns a float, its a single dimensional value expressing vector length. It looses directional information but provides the length information which we can use to control the speed of the vector.

Normalization is a bit of an opposite operation – it returns vector direction, guaranteeing that the magnitude of the resulting vector is one. This means it looses the magnitude information but preserves the direction information which we can use to know where the game object is moving or to move a game object in a specific direction.

Источник

Понимание векторной арифметики

Сложение

При сложении 2 векторов результат эквивалентен тому, что получится если исходные векторы принять за следующие друг за другом “шаги”. Заметьте, что порядок двух слагаемых не важен, т.к. в любом случае результат будет одинаковый.

что такое vector3 в unity. VectorAdd. что такое vector3 в unity фото. что такое vector3 в unity-VectorAdd. картинка что такое vector3 в unity. картинка VectorAdd.

Если первый вектор принять за точку в пространстве, то второй вектор можно интерпретировать как сдвиг или “прыжок” из этой точки. Например, чтобы для поиска точки 5-тью единицами выше точки на земле, вы могли бы использовать следующий расчёт:-

Вычитание

Вычитание векторов чаще всего используется, чтобы узнать расстояние и направление одного объекта относительно другого. Заметьте, что при вычитании порядок параметров имеет значение:-

что такое vector3 в unity. VectorSubtract. что такое vector3 в unity фото. что такое vector3 в unity-VectorSubtract. картинка что такое vector3 в unity. картинка VectorSubtract.

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

Скалярные умножение и деление

Говоря о векторах, в порядке вещей обращаться к обычным числам (например, значениям типа float) как к скалярам. Это значит, что у них есть только “размер” или величина, в то время как у векторов есть и величина и направление.

Умножение вектора на скаляр даёт в результате вектор, с тем же направлением, что и исходный вектор. Тем не менее, величина нового вектора равна исходной величине умноженной на скалярное значение.

Аналогично, скалярное деление делит исходную величину вектора на скаляр.

Эти операции полезны, когда вектор представляет из себя смещение движения или силу. Они позволяют вам изменить величину вектора без влияния на его направление.

Скалярное произведение (Dot Product)

что такое vector3 в unity. DotProduct. что такое vector3 в unity фото. что такое vector3 в unity-DotProduct. картинка что такое vector3 в unity. картинка DotProduct.

Если работать с точки зрения углов, то можно достаточно просто найти соответствующие косинусы используя калькулятор. Тем не менее, полезно иметь интуитивное понимание основных значений косинуса, как показано на диаграмме ниже:-

что такое vector3 в unity. CosineValues. что такое vector3 в unity фото. что такое vector3 в unity-CosineValues. картинка что такое vector3 в unity. картинка CosineValues.

Векторное произведение (Cross Product)

Другие операции предназначены для 2D или 3D векторов и для действительных векторов с любым числом измерений. Векторное произведение же, напротив, имеет смысл применять только для 3D векторов. Оно использует 2 вектора как входную информацию и возвращает ещё один вектор в качестве результата.

Итоговый вектор перпендикулярен двум исходным векторам. Можно использовать “правило левой руки”, чтобы запомнить направление выходного вектора относительно исходных векторов. Если первый параметр совпадает с большим пальцем руки, а второй параметр с указательным пальцем, то результат будет указывать в направлении среднего пальца. Если использовать обратный порядок параметров, то тогда итоговый вектор будет указывать в противоположном направлении, но его величина не изменится.

что такое vector3 в unity. LeftHandRuleDiagram. что такое vector3 в unity фото. что такое vector3 в unity-LeftHandRuleDiagram. картинка что такое vector3 в unity. картинка LeftHandRuleDiagram.

Величина результата равна произведению величин исходных векторов, умноженному на синус угла между ними. Некоторые полезные значения функции синуса указаны ниже:-

что такое vector3 в unity. SineValues. что такое vector3 в unity фото. что такое vector3 в unity-SineValues. картинка что такое vector3 в unity. картинка SineValues.

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

Источник

Что такое vector3 в unity

С этого урока будут рассматриваться вектора. Но так как в Unity три класса векторов (Vector2, Vector3, Vector4), условное обозначение «общего» класса: Vector[X].
Т.е. если функция есть не только в одном классе, то буду писать Vector[X].Функция.
В коде «общий» класс использоваться не будет.

Интерполяция 1

Первая функция интерполяции векторов в Unity (C#):

Данная функция получает промежуточное значение (интерполирует) между векторами a и b на основе t.
При t равное 0 (или меньше) вернёт a. При t равное 1 (или больше) вернёт b. При t равное 0.5 вернёт среднее значение между a и b.

Применение

Можно изменить пример из урока 9 (Mathf Интерполяции):
что такое vector3 в unity. inverse interpolate 001. что такое vector3 в unity фото. что такое vector3 в unity-inverse interpolate 001. картинка что такое vector3 в unity. картинка inverse interpolate 001.

В данном случае персонаж изменяет свои координаты по нескольким осям сразу (если конечная точка не на одной оси с персонажем). Из точки А в точку Б персонаж доберётся за одну секунду.
Можно поделить Time.time на какое-нибудь число, чтобы персонаж двигался медленнее (например на 60, тогда он доберётся за одну минуту).

Интерполяция 2

Вторая функция интерполяции векторов в Unity (C#):

Возвращает промежуточное значение между векторами a и b на основе t (t в промежутке от 0 до 1).
В отличии от Lerp эта функция возвращает значение не на прямой, а на дуге.
Для лучшего понимания рассмотрим пример:
Персонажу всё ещё надо из точки А попасть в точку Б, но у него на пути есть препятствие.
что такое vector3 в unity. vector interpolation 001. что такое vector3 в unity фото. что такое vector3 в unity-vector interpolation 001. картинка что такое vector3 в unity. картинка vector interpolation 001.

В данном случае персонаж не будет идти на прямую пытаясь пройти сквозь стену, а пойдёт по дуге (за одну минуту).

Источник

Как работают векторы. Баскетбол на Unity 3D

Учебные материалы для школы программирования. Часть 16

В этой статье, мы обратим свой взор в прошлое, и вспомним, с чего начиналась детская школа программирования Step to Science. Первоначальная идея проекта состояла в том, чтобы быть не просто кружком технического творчества, а стать для детей ответом на вопрос, «зачем учиться в школе?»

К чему нам физика, алгебра и геометрия, если мы не планируем проектировать космические корабли, если для счета у нас есть калькулятор в телефоне, расплачиваемся мы чаще картой, так что даже сдачу в уме считать не надо.
Я тоже в детстве вела такие рассуждения, и у родителей не было иных способов донести до меня истину, кроме фразы «нет слова не хочу, есть слово надо» и ремня, который без лишней полемики мотивировал садиться за уроки.

Порядок выполнения

На примере создания 2D игры «баскетбол», рассмотрим векторы (скорости, сил, локальной и глобальной систем координат). Разберем принципы представления систем координат и представления векторов. Также будет затронута работа с LineRenderer и многокамерность.

Создадим новый проект и импортируем в него приложенный ассет.
Ассет содержит в себе все ресурсы, необходимые для создания полноценного 2D приложения.

Для начала создадим небольшую сцену, в качестве фона выберем спрайт «спортзал» и установим на него сетку. Обратите внимание, что необходимо выставить коллайдеры для щита и корзины.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Конечно, необходимо выставить правильный Order in layer у спрайтов. Добавим мяч, применим к нему Circle collider и Rigidbody.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

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

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Чтобы воспроизводить этот звук, напишем простой скрипт, закинем его на мяч и сконфигурируем.

В скрипте нет автопоиска Rigidbody, так что придётся закинуть его руками. Если нажать на Play, наш мяч упадёт, издавая звуки. Чтобы мяч отскакивал, создадим физический материал и закинем его на коллайдер мяча.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Теперь подумаем о том, чтобы мяч показывал своё направление. Для этого создадим скрипт, который рисует стрелки: нам понадобятся два пустых объекта с LineRenderer, один в другом.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Создадим материал для стрелки:

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

И добавим скрипт, который будет выставлять вершины LineRenderer’ов, делая из них стрелки:

Закинем скрипт на объект-родитель стрелки и настроим его.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Теперь надо написать скрипт, который будет вектор скорости передавать в наш скрипт «показывания» стрелки. Он очень простой:

Закинем его на мяч, в скрипте укажем риджибади мяча и объект со скриптом стрелки.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Теперь сделаем так, чтобы мяч можно было кидать. Для этого необходимо выставить ему тип Rigidbody как Kinematic и написать небольшой скрипт.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Скрипт выкладываем на пустой объект в мире и устанавливаем ему наш мяч в качестве риджитбади и его трейл.

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Внутри панели должен лежать спрайт со следующими параметрами (обратите внимание на привязку):

что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader. что такое vector3 в unity. image loader. что такое vector3 в unity фото. что такое vector3 в unity-image loader. картинка что такое vector3 в unity. картинка image loader.

Для того, чтобы при компиляции не возникало ошибок из-за отсутствия класса спавнера, данный скрипт приложен отдельным ассетом, и импортировать его можно только после создания спавнера.

Для того, чтобы сделать включение/выключение стрелок, используется скрипт Toggle, который реализован через эвент-систему юнити. Его необходимо закинуть на кнопку и сконфигурировать следующим образом.

Источник

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

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