Что такое vector в unity

Обновлено: 04.07.2024

Vectors are a fundamental mathmatical concept which allow you to describe a direction and magnitude. In games and apps, vectors are often used 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.

Для положительных значений

Debug.log (новый Vector2 (1, 2) - новый Vector2 (3, 2));

Dot Product

The dot product takes two vectors and returns a scalar. This scalar is equal to the magnitudes of the two vectors multiplied together and the result multiplied by the cosine of the angle between the vectors. When both vectors are normalized, the cosine essentially states how far the first vector extends in the second’s direction (or vice-versa - the order of the parameters doesn’t matter).


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 :


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.

For example, a car’s speedometer typically works by measuring the rotational speed of the wheels. The car may not be moving directly forward (it may be skidding sideways, for example) in which case part of the motion will not be in the direction the car is facing - and so won’t be measured by the speedometer. The magnitude of an object’s rigidbody A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary .velocity vector will give the speed in its direction of overall motion but to isolate the speed in the forward direction, you should use the dot product:

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.

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:-

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:-


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.

Для отрицательных значений

Print (-новый Vector2 (1, 2));

Что такое Vector2 и Vector3 в Unity?

Название говорит обо всем. Я часто вижу их в сценариях движения, если это помогает. Что такое Vector2 и Vector3, документы Unity немного сложны для новых людей.

Примеры кода

Vector2

Это представление двухмерных векторов и точек, используемых для представления двухмерных позиций только по двум осям x и y.

UNITY3D Как проверить вектор направления моей камеры?

Я новичок в Unity. У меня есть игра с режимом FPS, камера вращается движениями мыши, а солнце - это направленный свет. Я должен написать сценарий, в котором я проверяю, находится ли солнце в поле зрения игрока. Я думал, что могу вычислить угол между двумя векторами, а затем решить, видно ли солнце. Первый вектор:

Но у меня проблема со вторым . Я не знаю, какую переменную мне следует использовать, camera.transform.forward ВСЕГДА (0,0,1) .

Вы можете помочь мне? Я буду очень благодарна.

Описание

Representation of 3D vectors and points.

This structure is used throughout Unity to pass 3D positions and directions around. It also contains functions for doing common vector operations.

Besides the functions listed below, other classes can be used to manipulate vectors and points as well. For example the Quaternion and the Matrix4x4 classes are useful for rotating or transforming vectors and points.

2 ответа

Есть несколько способов добиться этого, но я предлагаю использовать Raycast. Я полагаю, что солнце - это больше, чем просто точка, у него есть некоторая область, видимая игроку, поэтому даже если он не видит центральную точку солнца, он все равно может видеть некоторую часть его области. Если это так, я рекомендую добавить новый скрипт к объекту sun, чтобы идентифицировать его программно. Затем убедитесь, что к нему прикреплен компонент-коллайдер размером примерно равным солнцу. Затем в вашем скрипте, в котором вы хотите определять видимость солнца игроку, вы можете сделать что-то вроде этого:

Итак, objHit! = Null означает, что игрок может видеть любую часть области, где есть солнце.

Скалярное произведение возвращает 1, когда два вектора выровнены, 0, когда они находятся под углом 90 градусов, и -1, когда они противоположны.

Значение указано в радианах, поэтому, если вам нужен угол обзора 90 градусов, это будет 45 градусов (так как 90 - это 45 слева и справа), и это примерно. 0.7f.

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).

Vector3

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

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.


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:-


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.

Ошибка внесения изменений

По определённым причинам предложенный вами перевод не может быть принят. Пожалуйста <a>попробуйте снова</a> через пару минут. И выражаем вам свою благодарность за то, что вы уделяете время, чтобы улучшить документацию по Unity.

Ваше имя Адрес вашей электронной почты Предложение * Разместить предложенное

Примеры кода

Vector3 offset = transform.position - player.transform.position;

1.transform.Translate (Vector3.forward * Time.deltaTime * speed)

  1. Debug.Log (Cube.transform.rotation) // куб - игровой объект

The Vector 3D response

Vector - это количество , которое имеет направление . количество называется величиной вектора, а проекция вектора на каждую ось равна упоминается как компоненты вектора.

Vector1 имеет 1D направление , например точку на линии, значение рулевого колеса или любое действительное число. например . (0) или (-1000) . Величина Vector1 равна абсолютному значению x компонента вектора или sqrt(x^2) .

Vector2 имеет 2D-направление , например точку xy в 2D-пространстве, или положение джойстика, или смещение точки uv на 2D текстуре. например . (0,0) или (-1, 100) . Величина Vector2 равна sqrt(x^2+y^2) .

Vector3 имеет 3D-направление , как точка xyz в 3D-пространстве, или цвет в формате RGB, или набор из трех чисел. например . (0,0,0) или (-0,1, 3,14, 30) . Величина Vector3 равна sqrt(x^2+y^2+z^2) .

Vector4 имеет направление 4D , как точка xyzw в пространстве 4D, или цвет в формате RGBA, или набор из четырех чисел. например . (0,0,0,0) или (0,1, 0,2, 0,3, 0,4). Величина Vector4 равна sqrt(x^2+y^2+z^2+w^2) .

Computing a Normal/Perpendicular vector

A “normal” vector (ie. a vector perpendicular to a plane) is required frequently during mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary generation and is also useful in path following and other situations. Given three points in the plane, say the corner points of a mesh triangle, you can find the normal as follows: - Pick one of the three points - Subtract it from each of the two other points separately (resulting in two new vectors, “Side 1” and “Side 2”) - Calculate the cross product of the vectors “Side 1” and “Side 2” - The result of the cross product is a new vector that is perpendicular to the plane the three original points lie on - the “normal”.



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.

3 ответа

Векторы - это математические модели, которые моделируют как направление, так и величину. Vector2 - это 2D, а Vector3 3D.

Вектор2 (1,5) - это направление с отношением 1 части x и 5 частей y. E.G линия на 1/6-й справа и 5/6-й вверх. Отрицательный сделает линию влево и вниз соответственно.

Величина шоу - это «сила» направления. Например, при использовании сил и физики нажатие чего-либо в векторе 2 (1,0) гораздо слабее вправо, чем векторе 2 (100,0).

Это должно быть введение в основную теорию для вас.

Vector3

Это представление трехмерных векторов и точек, используемых для представления трехмерных положений с учетом осей x, y & z.

Читайте также: