Magnitude unity что такое
Перейти к содержимому

Magnitude unity что такое

  • автор:

Vector3.magnitude

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.

Your name Your email Suggestion * Submit suggestion
public var magnitude : float;
public float magnitude ;

Description

Returns the length of this vector (Read Only).

The length of the vector is square root of (x*x+y*y+z*z) .

If you only need to compare magnitudes of some vectors, you can compare squared magnitudes of them using sqrMagnitude (computing squared magnitudes is faster).

Vector3.magnitude

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.

Your name Your email Suggestion * Submit suggestion

public float magnitude ;

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

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:

Img 1

In game development, vectors are mainly used to describe the position of a game object, and to determine its speed and direction.

Vectors can be expressed in multiple dimensions, and Unity provides Vector2, Vector3 and Vector4 classes for working with 2D, 3D, and 4D vectors.

We will be mainly focused on Vector2 and Vector3 since they are used when developing 2D and 3D games with Unity game engine.

Vector2 And Vector3 In Unity

We already mentioned that in game development vectors describe the position of a game object, it’s the same with Unity.

A Vector2 object describes the X and Y position of a game object in Unity. Since it’s a Vector2, and it only describes X and Y values, it is used for 2D game development.

In a 2D game, if you move a game object with an x amount of units on the X axis, and x amount of units on the Y axis you will get the position of that game object:

Img 2

The same goes for a 3D game, except that you can move the game object on X, Y, and Z axis in the game space:

Img 3

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

Img 4

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:

Img 1

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 testVector = new Vector3(10, 15, 20); float testVectorMagnitude = testVector.magnitude;  

Calling .magnitude on a vector variable will return the magnitude of that vector. And if you hover over the magnitude word in the code, you will see the explanation which states that magnitude will return the length of the vector, which is what we explained using the image above:

Img 5

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:

 private float speedX, speedZ, moveSpeed = 10, maxSpeed = 100; Vector3 tempVector; void Update() < speedX = Input.GetAxisRaw("Horizontal"); speedZ = Input.GetAxisRaw("Vertical"); tempVector = transform.position; // if the speed of the vector is less than the // maximum allowed speed if (tempVector.magnitude < maxSpeed) < tempVector += new Vector3(speedX, 0f, speedZ) * (moveSpeed * Time.deltaTime); >transform.position = tempVector; >  

The same goes for calculating the speed of a rigidbody. Since

 rigidbody.velocity  

is a vector, we can get the speed of that rigidbody by calling

 rigidbody.velocity.magnitude  

and we can use this information to limit the movement speed of the rigidbody the same we limited the movement speed of the Transform component in the example above.

We can also use the magnitude to calculate the distance between two vectors. If we have two vectors, a and b, then:

 (Vector A - Vector B).magnitude  

is the distance between these two vectors. This is what the Vector3.Distance function actually does.

Squared Magnitude

As we already saw from the examples above, we can use .magnitude to calculate the magnitude of a vector in Unity.

What happens behind the scene is that Unity is doing that calculation using the math formula we saw, which is magnitude = √a2 + b2. And for 3D we would add the extra Z axis.

There is a faster way how we can calculate the magnitude of a vector which does not involve using square root in the operation and that is using sqrtMagnitude:

 float sqrtMagnitude = someVector.sqrMagnitude;  

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:

 private Vector3 vectorA, vectorB; private float maxDistance, maxSpeed; float vectorA_Speed = vectorA.sqrMagnitude; // multiple the max speed with itself // to make it a squared value float maxSpeedSquared = maxSpeed * maxSpeed; // comparing the maximum speed if (vectorA_Speed > maxSpeedSquared) < >// calculating the distance between Vector A and B float vectorAB_Distance = (vectorA - vectorB).sqrMagnitude; // multiple the max distance with itself // to make it a squared value float maxDistanceSquared = maxDistance * maxDistance; // comparing the distance between Vector A and B if (vectorAB_Distance > maxDistanceSquared) 

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:

 private Vector3 vectorA; Vector3 vectorA_Direction = vectorA.normalized; // or vectorA.Normalize();  

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:

Img 6

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.

 // right direction Vector3 right = new Vector3(1, 0, 0); // left direction Vector3 left = new Vector3(-1, 0, 0); // up direction Vector3 up = new Vector3(0, 1, 0); // down direction Vector3 down = new Vector3(0, -1, 0); // forward direction Vector3 forward = new Vector3(0, 0, 1); // backward direction Vector3 backward = new Vector3(0, 0, -1);  

Depending on the axis, adding 1 or -1 value will point to a certain direction. This is connect to Unity’s coordinate system which looks like this:

Img 7

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.

What Is The Use Of Normalized Vectors

We already saw that normalizing a vector will return the direction of the vector, but why bother using normalization?

Why can’t we just use magnitude for the same purpose because using the magnitude we can calculate the distance between two vectors, which means we can calculate the distance between the current vector and the destination where we want to go, and we can use that information to move the game object in the desired direction.

While the claim above is true, we can calculate the length between vector A and vector B, but the problem is that vector A and B could be anywhere and at any distance, so magnitude could be anything.

Let’s say that we want to move object A 0.5 units towards object B. We can calculate the distance between object A and B using the magnitude, but we don’t have any means to calculate how to move object A towards object B by 0.5 units.

So in this case, we would subtract the distance between B and A and the multiple that by 0.5 and this is how we would move object A towards object B by 0.5 units.

This is how it would look like in the code:

  private Vector3 vectorA, vectorB; // calculate the direction Vector3 movementDirection = (vectorB - vectorA).normalized; // move vector A towards vector B by 0.5 unitys vectorA += movementDirection * 0.5f;  

Conclusion

The magnitude of the vector determines the length of that vector and we can use it to calculate anything related to speed of that vector.

This is useful if we want to control the speed of a game object or even calculate the distance between two game objects.

With normalization we get the direction of the specified vector. We can use this information to move game objects around and even create enemy AI.

If we want to move a game object from point A to point B, we can use normalization to determine the direction we need to go and then multiply the normalization value by x amount of units we want to move the game object which will make the game object move from point A to point B by the specified amount of units.

Vector3.magnitude and vector3.normalized explanation

I am looking at this code and do not know what is this magnitude and normalized doing and how is this guy using them. In documentation there is only few thing but it doesn’t explain much. Code i am looking at is:

public float minDistance = 1.0f; public float maxDistance = 4.0f; public float smooth = 10.0f; Vector3 dollyDir; public Vector3 dollyDirAdjusted; public float distance; void Awake() < dollyDir = transform.localPosition.normalized; //What has he got with this? Documentation says Returns this vector with //a magnitude of 1 so if i get it it return's it's length as 1. So what is the point? distance = transform.localPosition.magnitude; //Have no idea what he got with this >void Update() < Vector3 desiredPos = transform.parent.TransformPoint(dollyDir * maxDistance); //I know what TransfromPoint does but what is he getting with this dollyDir * maxDistance //Some other code which i understand >

And while i am here if someone could explain me Mathf.Clamp Documentation for clamp is so unclear and how i got it is that i give top and bottom value 1 and 5 and if i set value = 3 it will return 3, but if i set value > 5 it will return 5 and if i set value < 1 it will return 1? Thanks.

asked May 7, 2018 at 10:24
Aleksa Ristic Aleksa Ristic
2,422 3 3 gold badges 24 24 silver badges 54 54 bronze badges

Just a suggestion, as it is extremely useful for 3D applications, you should try and learn some linear algebra. Khan Academy has a decent course on it.

May 7, 2018 at 12:10
Thanks. I am getting into it 🙂
May 8, 2018 at 4:39

3 Answers 3

Vector3.magnitude returns a float, its a single dimensional value expressing vector length (so it looses directional information)

Vector3.normalized is a bit of an opposite operation — it returns vector direction, guaranteeing that the magnitude of the resulting vector is one, (it preserves the direction information but looses the magnitude information).

The two are often useful for when you want to seperate those two ways of looking at a vector, for example if you need to have an influcence between two bodies where the influence is inversly proportional to the distance between them, you can do

float mag=(targetpos-mypos).magnitude; if (mag

this is the most typical use case for me, I am not sure what the author of the original code meant by his as it does seem he could just use a vector difference without using the two extra calls

Mathf.Clamp returns value of value lies between min and max, returns min if its lower and max if is greater.

Another interesting feature of Vector3 is sqrMagnitude which returns a^2+b^2+c^c without computhing the square root. While it adds a bit to the complexity to the code (you need to compare it with squared distance), it saves a relatively expensive root computation; The slightly optimised but a tiny bit harder to read version would look like this

Vectior3 delta=targetpos-mypos; if (delta.sqrMagnitude

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

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