The use of vector geometry in game Programming 2

Source: Internet
Author: User
Tags constant cos dashed line reflection relative

For the first time, I said a little bit. The basic content of vector knowledge and a bit of usage skills, the simple display of its role in game programming. This time, take full advantage of the nature of the vector to imitate a physical phenomenon.

First, I would like to introduce the two basic but very important techniques that will be used.

One, the vector b orthogonal to a certain vector a



Depending on the nature of the inner product of the vector and the relationship between the orthogonal vectors, there are:

Set a= (Xa,ya),b= (XB,YB)

a.b = 0
= = Xa*xb + ya*yb = 0
= = XA*XB =-ya*yb
= = Xa/-ya = Yb/xb
= XB =-ya, YB = xa or xb = ya, YB =-xa

The orthogonal vector of the vector (Xa,ya) is (xb,yb) = (-YA,XA)
For example, in the image above, the vector (2,3) is rotated counterclockwise by 90 degrees and the orthogonal vector is ( -3,2) and rotates 90 degrees clockwise (3,-2).

Thus, given a non-zero vector (x, y), the orthogonal vector (-y,x), which rotates counterclockwise by 90 degrees relative to the axis, turns 90 degrees clockwise to the orthogonal vector (y,-x).



Second, the calculation of a vector b and another constant quantity a collinear two opposite projection vector

Let's take a look at the diagram above, obviously, CosA (a=x) about the y-axis symmetry, is even function, so cosA = cos (-a),
And because CosA is a periodic function, and the period is 2*PI, there is a cos (a+2*pi) = CosA = cos (-a) = cos (-A+2*PI),
Then according to cosa = cos (2*pi-a) and a.b = | a|*| b|*cosa, yes.

a.b = | a|*| b|*cosa = | a|*| b|*cos (2*PI-A)




Now, according to the above image, there is a.b = | a|*| b|*cosa = | a|*| b|*cos (2*pi-a) = Ax*bx + Ay*by

According to this rule, when the abovebAndCWhen the modulus is equal, there is |a|*|b| = |a|*|C|, further, when they were withaWhen the angle A = B, there is

a.b= |a|*|b|*cosa = |a|*|C|*COSB =A.C, the corresponding has
a.b= |a|*|b|*cosa = |a|*|b|*cos (2*pi-a) = |a|*|C|*COSB = |a|*|C|*cos (2*pi-b) =A.C That is
AX*BX + ay*by = ax*cx + ay*cy

We also note that in a cycle, such as in [0,2*pi], Cosa has two positive and negative conditions, namely: In (0,PI/2) & (3*PI/2, 2*PI) is positive, in (PI/2,3/2*PI) is negative. Well, after knowing this, look again.a.b= |a|*|b|*cosa,|a| and |b| All are positive, soa.bThe positive and negative is decided by Cosa, in other words,a.bThe cosine cos of their angle A has the same symbol. So, looking at the diagram above, we have:

1) when a in (0, PI/2) & (3*PI/2, 2*pi), at this time 2*pi-a in (-pi/2,0) & (0, PI/2), a.bis a positive
2) when a in (PI/2, 3*PI/2), at this time 2*pi-a also in (PI/2, 3*PI/2), a.bis negative


Now let's look at what is the relationship between the two inner product of a vector b and B ' and the same vector a with the opposite of the same mode (angle is pi).
First B + b ' = 2*pi-pi = PI, so there are b = b ', b ' =-B, i.e.

(bx, by) = (-B ' x,-B ' y) =-(c ' x, C ' y)
(b ' x, b ' y) = (-bx,-by) =-(bx, by)

So
A.B =
(ax, ay). (bx, by) = (ax, ay). -(b ' x, b ' y) = a.-b '=-(a. B ')
a.b '= (ax, ay). (b ' x, b ' y) = (ax, ay). -(bx, by) = A.-b =-(a.b)

We see that a vector b of the same mode opposite vector B ' and the inner product of vector a a.b ', equal to the opposite number of the inner product of B and a -(A.B).

Well, with the above foundation, we can ask for a vector b with another constant quantity a collinear two opposite projection vectors C and C ' .

Request B on a projection vector C, we can use a number multiplied by a unit vector, this unit vector and a direction one to, we remember as A1. And this number is the projection length of b on a .

First, to find the unit vector A1, we know that it is vector a multiplied by its own length of the reciprocal (number multiplication vector), its length we
You can find that M = sqrt (ax^2 + ay^2), so A1 is (ax/m, ay/m), recorded as (A1x, a1y).

Projection length/c/(note//with | | The difference between the former is the projection length, can be negative or zero, the latter is the actual length, the balance is non-negative. According to the geometrical meaning of the inner product: a vector b -point is multiplied by another vector A1, which is equal to the long product of the long and A1 of the projection of B on A1 . So we're going to ask B to have a long projection on a , just use it to multiply the unit vector of a , A1 , because the unit vector is 1 long , B's projection length C/Multiply by 1 is also equal to the projection length itself, namely:

/c/ = B.A1 = (bx, by). (a1x, a1y) = bx * a1x + by * a1y

Well, we got the projection length of C , and now we can find out C:

c =  / C /* A1 =  (BX * a1x + by * a1y) *a1x, (BX * a1x + by * a1y) *a1y

To summarize, is C  = ( b . A1 ) * A1.

We see that the angle between B and A1 is between (0, PI/2), so their dot product/ C /is a positive value. So when it is multiplied by A1 , the direction of the vector is the direction of the A1 .

now looks at B ' , which is the same-mode opposite vector of B , and the angle between the A1 is between (PI/2, 3*PI/2), so The B ' point is multiplied by A1 to get the/ C ' /is a negative value, which is then multiplied by A1 to get the direction of the vector and A1 instead. We know , a vector b of the same-mode opposite vector B ' with vector a inner product a.b ' , equal to the inverse number of B and the inner product of a - ( a.b ). Therefore,/ c '/=-/ c /, that is, their absolute values are equal and the symbols are reversed. So they multiply by a A1 , and the resulting two modulo equality vector C is collinear with C ' .

Let's finish it:

( B ' . A1 ) =-( b.a1 )  
= ( B '. A1 ) = ( b.a1 ), good, substituting C  = ( b . A1 ) * A1 , get

C= -(B '. A1)*A1
= (B '. A1)*A1=-C = "

c = (b. A1)
*A1 = (-B '. A1)*A1
C ' = (b '. A1)
*A1 = (-B. A1)*A1

So far, we have come to the conclusion that when a vectorbwith another vectoraThe angle between (0, PI/2) & (3*PI/2, 2*PI), it is inaThe projection vector in the directionCIt isC = (b. A1)*A1, whereA1Isathe unit vector;aProjection vector in the opposite directionC 'IsC ' = (b '. A1)*A1,where vectorB 'IsbInverse vector of the same mode.

Conversely, it is also possible to say: when a vectorB 'with another vectoraThe angle between (PI/2, 3*PI/2), it is in theaProjection vectors in the opposite directionC 'Is
C ' = (b '. A1)*A1, whereA1Isathe unit vector;aThe projection vector in the directionCIsC = (b. A1)*A1。 where vectorbIsB 'Inverse vector of the same mode.

In particular, multiply the two-unit vectors to get the cosine of their angle :

E. E = | E|*| E|*cosa = 1*1*cosa = CosA

Well, it's over. Now you can look at it.



Three, the principle of using vectors to simulate any angle bounce

According to Elementary physics, the contact surface will be deformed to produce the elasticity of interaction when the interacting objects are subjected to the relative moving trend of the contact surface of the external force.
Elasticity causes the deformation or deformation of an object to change as the motion forms. After knowing about this, we begin to discuss the following situation in detail:



Rectangular box and small ball collision, collision time is very short, the wall is infinitely smooth so that collision process without friction, collision time is very short, no energy loss ... In short it is an ideal physical environment. We discuss in this ideal environment that the ball has a completely elastic collision with the wall and the angle of incidence is equal to the reflection angle: a=a ', b=b ', C=c ',...。 The dashed line is normal , and it is perpendicular to the wall surface. The ball will collide indefinitely in the rectangular frame, and the angle of incidence and the angle of reflection are equal during each collision.


Let us be specific, now assuming that the upper side of the rectangle wall is parallel to the X axis, and the left and right sides are parallel to the Y axis. This is very good, when we write the program as long as the ball hit the upper and lower surface when the Y-direction of the speed of the value of the return to the left and right surface when the X-direction velocity value is returned to the line, this method is often used in simple physical models and rules bounding box game programming, which simplifies many programming steps, This can be done when writing simple games. But the facts are not always as good as they want to be. If the situation looks like this:



Although the incident angle is still equal to the reflection angle during the collision, but the angle of the boundary is not so "pure", their angle is arbitrary, so it is not easy to take the x direction or the y direction of the speed of the return, we have to find another solution.

Our task now is to find the object's velocity vector S and the boundary vector B, and ask for its reflection vector F. Let's take a look at what vector relationships are in the process of collisions:



Setbis the obstacle vector,Sis the incident velocity vector,Fis the reflection velocity vector, which is the vector we want to calculate. A is the angle of incidence, a ' is the angle of reflection, A=a '.NIsbThe normal vector, i.e.NPerpendicular tobNis withNVector of collinear lines,N 'IsNThe unit vector for the direction.Tis perpendicular toNThe vector. According to the vector addition, there is now a relationship:

(1)S+N=T
(2)N+T=F

Merge, get

F=T-S

We've found the calculations.F's formula. Over hereSis known, we want to calculateT, see (1) Type:

T=S+N

To calculateTSis known, it is necessary to calculateN。 We knowNIsSInNIn the direction of the projection obtained,SKnown so to getNWe need to calculate it again.N, whileNAgain andbThe vertical. Remember the two tips for using vectors we've just exported, and we'll use them here:

1, given a non-zero vector (x, y), it is relative to the axis counterclockwise to 90 degrees of the vertical vector (-y,x), clockwise to 90 degrees vertical vector (y,-x).

2. When a vectorbwith another vectoraThe angle between (0, PI/2) & (3*PI/2, 2*PI), it is inaThe projection vector in the directionCIt isC= (B. A1) *A1, whereA1Isathe unit vector;aProjection vector in the opposite directionC 'IsC '= (B '. A1) *A1, where the vectorB 'IsbInverse vector of the same mode.


Yes, we got it.b, with tip 1 you can figure outN。 and then normalization.NCalculates theN ', and then with Tip 2, hereSAndN 'The angle between (PI/2, 3*PI/2), so you want to useC= (B. A1) *A1, you must makeb= -S,A1=N '。 This will calculate theN。 And according to the above (1) formulaT, all right, here we are.TAndF=T-S, you have it all.


The calculatedFis the velocity vector after the collision of an object, in 2-d it has two components X and y,3-d with three components. It is also proved that one of the advantages of using vectors is that they do not have to consider the coordinate problem in some similar relationship derivation process, and the direct use of simple vectors can be done.

Here, watch our obstacle vectors.bThe actual programming is calculated by subtracting the two endpoint coordinates of the barrier, and the order of subtraction is not considered when calculating. Because although we get it in different order of subtractionbIn the opposite direction, and the calculated unit normal vectorN 'The opposite direction (the dashed part of the image), but when used- SGo to Dot by unit method vectorN 'The resulting value is reversed, and it has an automatic adjustment function: now suppose tobFor the boundary,SThe side is in the positive direction. If the unit method vectorN 'is the positive direction, with- SThe dot product value is also positive, positiveN 'And then multiply it to the right.NIf the unit normal vector is in the negative direction,- SThe dot product value is also negative, negativeN 'and multiply the negative dot product to get it.Nis in the positive direction. AnywayNThe direction is constant, the calculatedFThe same is true of course.

Four, the code to achieve it

Now I want to code to implement it, but before one point I would like to say, perhaps the reader has thought, before the rebound we have to determine when to start the rebound, that is, when the collision, this is a collision detection problem, originally this is the problem we should first solve, but I want to put it next time in the specific said, So here the code omits the collision detection step and calculates the bounce speed vector directly. The aim is to quickly use the above theory in the algorithm.




In the game loop
The moving object is reduced to a particle, and the position is x=0.0f,y=0.0f
The component of the particle velocity vector is svx=4.0f,svy=2.0f
The obstacle vector is bx=14.0f-6.0f=8.0f,by=4.0f-12.0f=-8.0f
Then the vertical vector of the barrier vector is nx=-8.0f,ny=-8.0f

Collision detection can be added here
Now assume that the collision is complete and start the bounce calculation.

Calculate the length of n
float lengthn = sqrt (nx*nx + ny*ny);
Normalized n is n '
float n0x = nx/lengthn; N0X is the X component of n '
float n0y = ny/lengthn; N0y is the Y component of n '
Calculates N, which is the projection vector of s in the n direction.
UnderB '= (-b.A1 ').A1 ', there are n = (-S.N '). N '
float NX =-(svx*n0x+svy*n0y) *n0x; X component of N
float NY =-(svx*n0x+svy*n0y) *n0y; Y component of N
Calculate T
T = S + N
Float Tx = Svx + nx; X component of T
Float Ty = Svy + ny; The Y component of T
With T, there's aF=T-S, okay, you have everything now.
Calculate F
float Fx = 2*TX-SVX; The X component of F
float Fy = 2*ty-svy; Y component of F
Now we've calculated the speed vector after the bounce.
Update Speed vector
SVX = Fx;
Svy = Fy;
Particle movement
X+=SVX;
Y+=svy;
Now you can see that the particle has been relentlessly bounced back.
And it's simulated in the ideal environment according to the laws of physics.


It is so simple, a physical phenomenon can be simulated, but not perfect, just for the line barrier, and no collision detection, the next analysis of the latter

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.