Unity3d mathematical basics and mathematical AIDS

Source: Internet
Author: User

Reproduced with smartdot: http://my.oschina.net/u/243648/blog/67193

1. Mathematical aids for Mathematics (dot multiplication/Cross multiplication)/unity3d

2. Coordinate System (local/World/screen)

3. Unity3d running process

4. Calculate the angle between the role and the target point, rotate the role toward the target point, and then move the role (example)

5. Gizmos/inspector/map editing

6. Data Interaction Between script files

7. Yield return/Collaborative thread/event

8. Socket

9. Unity3D calls c ++ DLL

---------------------------------------------------------------

---------------------------------------------------------------

 

1. Basic Mathematical knowledge required in Unity3d (vector/matrix/transform)

I think these words are quite common in game engines, and unity3d is no exception! Although unity encapsulates us so well that we can use it, it is helpful to ourselves. What if I use another engine in the future? If you don't want to be restrained by these tools all your life, you must understand these boring mathematical knowledge. Of course, I will not discuss complex mathematical knowledge here. Of course I am interested in it. I can focus more on it, but I don't have to spend much time on it (except when I want to be a mathematician ), if you don't understand it, you can take a look! With this knowledge, you can look at the mathematical auxiliary classes that unity3d has given me, and it will be much easier to use!

1. vector)

Vector has two important attributes: length and direction. Let's take an example! Moving objects in a space must know the movement direction and distance of objects. It is very convenient to describe objects using vector, as well as the camera's observation direction and light direction.

It does not contain location information, so it can be independent from the coordinate system. It can be considered equal as long as the vector length and direction are the same. The introduced coordinate system does not add additional information to the vector. Therefore, the position of a vector does not affect its attributes. When discussing positions and vectors, there is a very confusing concept: Point and vector. In unity3d, sometimes a point is described using the vector class, this is because the vector contains three float variables: x, y, and z. If Vector (x, y, z) is a vertex or a Vector, consider it carefully. Or, if I have any knowledge, I want to inform you.

The concepts of the unit vector and the model of the vector are very basic and important. I will not repeat the specific concepts, but I need to know the functions of these two vectors. The unit vector can be used to represent the direction, and the modulo can be used to represent the distance. We can use these two concepts to calculate the moving distance and direction of an object. As for object rotation, vector calculation is involved, which will be mentioned later.

Vector operations include addition, subtraction, multiplication, and cross product. mathematical computation and concepts are not mentioned for operations. Baidu knows that everyone is a cultural person. Haha, just kidding! For example! Imagine that you are tracking the movement of an object, and you find that your tracking direction has been deviated. How do you modify the direction? If you use your eyes, you can, but the computer is blind! Press your eyes on the computer! The computer only performs numerical computation. Of course, you must use a mathematical model to describe it and then calculate it! At this time, you can use vector subtraction to draw the image of vector subtraction. Is it very convenient to solve it! For another example, if you want to chase an object, he always turns east and west. I want to speed faster than him, but if the direction is wrong, it is difficult to intercept him down, what should I do? Imagine the vector addition graph, based on the speed of two people, as long as my speed is faster than you, use vector addition and multiplication (Multiplication can be used to control the speed ), I can give you a wooden stake on the road, so that you will be killed. For another example, if I want to know the angle of the target object, I can use the dot product to calculate the angle of the target object. There are still many examples. If you are too reluctant to give them a question, you will be the champion of weightlifting and give a connection:

Http://wenku.baidu.com/view/f279471514791711cc79176a.html

After talking about the vector, I want to mention a small detail, which is very necessary. Because the x, y, and x types of vectors are float. Due to the inaccuracy of float, we should consider that two floating points with equal values may have certain errors. We can see that two floating point numbers in some game codes are equal, which may be like this:

Const float EPSILON = 0.001f; // error range

Bool Equal (float num1, float num2)

{

// As long as num1 and num2 are in the error range, they are considered equal to true. Otherwise, false values are returned.

Return fabs (num1-num2) <EPSILON? True: false;

}

2. matrix and Transformation)

What is matrix used? The university teacher did not tell us. Why not tell us? I will not discuss it any more. I am actually an amateur! After all, the teacher did not tell me. I hope to correct me if I am wrong!

In mathematics, a matrix is composed of the coefficients and constants of the equations. In terms of mathematical principles, a matrix represents a transformation from a linear space to another linear space.


Using a textbook example, we can briefly describe the calculation formula, which is probably a relatively stupid reason. I don't like to describe it directly with mathematical symbols, but just like to look at pictures.


 


To put it bluntly, my personal understanding is to allow you to "traverse" and convert your vectors from one space to another, moving (or rotating) one position) to another location. As for the space, there will be a local coordinate system, a world coordinate system, and a screen coordinate system. We will discuss it later! In my opinion, there are several matrix transformations: translation, rotation, scaling, and unity3d are all encapsulated. I want to see how they changed. I am too lazy to draw a picture on the network! According to the matrix algorithm, multiply the vector by the transformation matrix and compare the values before and after conversion!

Each transformation has a corresponding transformation matrix. The transformation can be completed by multiplying the vectors or coordinates by the transformation matrix. Multiplication and superposition can also be performed between transformation matrices. The geometric meaning of superposition is to combine the transformation into a matrix in the order of superposition. Note that matrix superposition does not meet the exchange law. The transformation matrix is a 4x4 matrix, so the vectors and coordinates need to be extended to the same space.
Vector: (x, y, z, 0)
Coordinates: (x, y, z, 1)
The difference between them is that the fourth item, where the first item of the vector is 0, can invalidate the translation transformation of the matrix without affecting the rotation and scaling operations. Take 1 for the 4th coordinates to make the translation valid, and the ratio of the translation transformation will not change. If 2 is used, the translation distance is twice that defined in the matrix. And so on. Note: after the conversion, 4th items may not be 0/1. In this case, we must perform a ing action to map it from the same space to a three-dimensional space, the method is simple:
(X, y, z, w) --> (x/w, y/w, z/w, w/w) --> (x/w, y/w, z/w, 1) --> (x/w, y/w, z/w)

3. plane and Ray)

Plane:

N Dot P + d = X;
X <0, point P is on the back of the plane, | X | the distance from point P to the plane
X> 0. point P is located on the front of the plane. | X | It is the distance from point P to the plane.
RAY:

Set the starting point to P0, the direction to u, and t as the parameter. t belongs to [0, infinity). When t belongs to (-infinity, + infinity), it indicates a straight line.
P (t) = p0 + t * u

The reason for putting them together is that they are often used together in actual development. At least I use a lot. Let's take an example!

For example, if we click the 2D screen coordinates to determine the position in the 3D space of the game, how can we determine it? How to use a two-dimensional mouse with only x and y axes to accurately obtain the positions of x, y, and z 3D spaces is a topic that has been discussed since the emergence of 3D. Even today, when graphics technology is so developed, 3D space clicks can only be said to be "probably accurate ". Clicking the mouse to determine the location of the 3D space has a great relationship with the camera. Why is there a great relationship with the camera? If you are familiar with the drawing flow in Direcx3D, you will know that the camera plays a key role in converting 3d space coordinates into screen coordinates, such as cropping and projection windows ), near cutting, remote cutting, and projection plane. Write a unity code segment! (If the code format is not well adjusted, you can check it out ).

Void Update ()

{

If (Input. GetMouseButtonDown (0 ))

{

RayControl ();

}

If (flagMove)

{

If (Vector3.Distance (transform. position, mousePos)> 1)

{

Transform. translate (transform. worldToLocalMatrix * ransform. forward * Time. deltaTime * 5); // transform. forward is the world coordinate, through transform. the worldToLocalMatrix conversion matrix is converted to the local coordinate and then moved in the local coordinate system. It is not necessary to move in the local coordinate system, but it must be unified.

}

Else

{

FlagMove = false;

}

}

}

Void RayControl ()

{

Ray ray = Camera. main. ScreenPointToRay (Input. mousePosition); // emits a Ray to the screen (note that this object is the main Camera)

If (Physics. Raycast (ray, out hit, 200) the X-ray length is 200 and the collision box on the ground is detected.

{

GameObject targetPos = GameObject. CreatePrimitive (PrimitiveType. Sphere); // instantiate a Sphere

TargetPos. transform. localScale = new Vector3 (0.5f, 0.5f, 0.5f );

MousePos = hit. point; // gets the coordinate of the collision point

MousePos. y = transform. position. y;

TargetPos. transform. position = mousePos; // put Sphere to the place where the mouse clicks

TargetDir = mousePos-transform.position; // calculates the orientation

Vector3 tempDir = Vector3.Cross (transform. forward, targetDir. normalized); // use cross multiplication to determine whether two vectors are in the same direction.

Float dotValue = Vector3.Dot (transform. forward, targetDir. normalized); // calculate the angle between two vectors and the angle between the role and the target point.

Float angle = Mathf. Acos (dotValue) * Mathf. Rad2Deg;

If (tempDir. y <0) // This field indicates that the two vectors are in the opposite direction. This judgment is used to determine whether the 30 degrees angle between the two vectors is clockwise or counterclockwise.

{

Angle = angle * (-1 );

}

Print (tempDir. y );

Print ("2:" + angle );

Transform. RotateAround (transform. position, Vector3.up, angle );

FlagMove = true;

}

}

 

Note: After writing it, it is found that there is no need to be so troublesome, so that transform. forward = (mousePos-transform.position). normalized can directly let the role toward the target RayControl function a lot of can save

4. unity3d mathematical AIDS

4.1 Mathf provides functions and constants for mathematical computation, with all functions required for mathematical computation. Mathf objects do not have constructor functions. They are inherent objects and are not classes of objects like strings. Therefore, Math () is not constructor ().

4.2 Matrix4x4 a standard 4x4 transformation matrix A transformation matrix can execute any linear 3D Transformation (for example, translation, rotation, scaling, cutting edge, etc.) and the pivoting transformation uses homogeneous coordinates. Matrix is rarely used in scripts: Vector3 and Quaternion are the most commonly used, and the functions of the Transform class are simpler. A matrix is used in special cases, such as setting a non-standard camera projection.

4.3 The Quaternion element is used to indicate that rotating them based on the plural is not easily understood. Therefore, you do not need to access or modify a single Quaternion component (x, y, z, w ); generally, you only need to take the existing rotation (for example, from Transform) and use them to construct a new rotation (for example, smoothing interpolation between two rotations ). You will use the four-element functions 99% of your time (other functions are used only)

Quaternion. LookRotation, Quaternion. Angle, Quaternion. Euler, Quaternion. Slerp, Quaternion. FromToRotation, Quaternion. identity.

4.4 Ray rays are infinite lines starting from origin and following the direction of ction

4.5 Rect a two-dimensional rectangle defined by x, y position, width, and height. The Rect structure is mainly used for 2D operations. The UnityGUI system is widely used, as well as camera positioning on the screen.

4.6 Vector2/vector3/vector4 represents the vector and point, and the structure is used to transmit 3D positions and directions in Unity. It also contains some common vector operation functions, such as angle, module, unit vector, cross multiplication, dot multiplication, forward to left to right, interpolation, projection, reflection, steering ........

4.7 In the last big manager, the position, rotation, and scaling of the transform object, each object in the scenario has a Transform. It is used to store and manipulate the position, rotation, and scaling of an object. Each Transform can have a parent level that allows you to apply positions, rotate, and scale horizontally. You can view the Hierarchy on the Hierarchy panel. They also support counters (enumerator), so you can traverse sub-objects cyclically.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.