Physics-achieving physical effects

Source: Internet
Author: User
Achieve physical effects

Now we can go into depth on the physics required for racing games. Today you can see many powerful physical engine functions, but because they are difficult to implement and are not written in. NET, you will implement the physical engine in your own way.

In this chapter, you have processed Vehicle Control and simple gravity effects. What is missing is an accurate collision detection system. When you hit a guardrail, your car should stop. You will also deal with complicated situations, such as through the annular orbit. It is not difficult to implement a Ring Orbit. With the track generation code in the previous chapter, you can easily add tracks by adding two sampling points. If your physical system can correctly handle the vehicle's stress, then driving along a ring track is almost automatically handled.

Handling annular tracks

Before you continue to implement the difficulties (collision detection and response, this is the main code of the CarPhysics class), please refer to figure 13-8, it shows when driving through a ring track, how to put the force on the car in a simplified way.


Figure 13-8

If you place the car on the top of the ring track without applying any external force, gravity (red) will pull the car down, so you cannot move or drive the car, because you will be disconnected from the track. Therefore, even to the top of the track, the car must always press to the track. This force must be greater than gravity, or your car will leave the track and start to fall (see Figure 13-9 ). It is important that you have enough impulse to keep your car on the track. The impulse is calculated by the force of the previous motion in the current frame.


Figure 13-9

If you leave it blank (first obtain the impulse on the previous ramp), gravity will pull you down. After a while, you will lose your impulse and eventually fall down. Because the Loop Track always changes the direction of the car, you can easily keep the car on the track. If the centrifugal force has a large gravity, it is easy to overcome the gravity. The example shown in Figure 13-10 is to pull a ball on the rope and rotate it. Even if the centripetal force is not strong, you can let the ball rotate, the faster the rotation, the smaller the impact of the ball's gravity, because the centrifugal force is also stronger, so it will be more difficult to hold the ball.


Figure 13-10

You can see that the centrifugal force pulls the ball away from your hand. When you turn very fast, the gravity is relatively smaller than the centrifugal force, even if you stop moving your hand, the impulse also moves the circumference of the position ball.

Elastic physics

Most of the formulas in the game have been simplified, and the sports of racing cars are not as complex as they are. You don't have to worry about the engine of a car or anything inside it. More driving parameters can be achieved through better braking and friction formulas using power, speed, start and brake acceleration. For a more detailed description of Automotive physics, see the following link http://www.racer.nl/reference/carphys.htm.

Because of the simplification of the automobile processing logic, many effects, such as the backward or forward of the brakes during the automobile acceleration, are not implemented. However, you can still implement some results in a simplified way.

All the wheels are attached to the spring to make the car more stable on the road. It takes some time for the wheel to accelerate the vehicle itself. This effect is more obvious when the brakes suddenly occur. Although the wheel has stopped, the car itself is still in motion. The quality of the CAR forces the whole car to tilt a little forward (see Figure 13-11 ).


Figure 13-11

Gravity always pulls you down, but different parts of the car, especially the wheels and other parts of the car, behave differently. The wheel connection spring enables the car to tilt forward and backward, which occurs during acceleration or deceleration, even if you just stay on the road, it is not necessarily flat (if you drive up the hill, the car will be deprecated ).

You don't need to have a spring or draw a wheel in the way of the S. If the car is leaning backward, the wheel will fall into the road, but because you do not observe the car from the side, you will not notice this situation. The camera is always behind the car. You can only see most of the tilt effects from the top and back of the car.

Because the effect is relatively simple, as long as the speed of the car changes, you can roll the car back and forth:

  • During acceleration, the vehicle is tilted backward-the greater the acceleration, the greater the elevation.

  • When braking, the car is leaning forward-the effect is usually stronger than the acceleration, because the braking acceleration is far beyond the acceleration.

In the previous game XNA Shooter, you have seen this effect. When you move in any direction, the flying boat will flip horizontally and vertically. The same formula can also be used for automobiles. To solve the problem that the wheel and other parts of the car will disappear on the road, you need to limit this effect:

// Calculate pitch depending on the forcefloat speedChange = speed - oldSpeed;// Limit speed change, never apply more than 8 mph change per sec.if (speedChange < -8 * moveFactor)  speedChange = -8 * moveFactor;if (speedChange > 8 * moveFactor)  speedChange = 8 * moveFactor;carPitch = speedChange;

When the speed of a car does not change, its pitch will remain 0. If it is accelerating or slowing down, the behavior of the car should also be correct. However, even with a better smoothing formula, this effect does not seem very convincing. In the real world, the race car will swing around until the spring loses all its power.

What you need now is a simple formula to let the car swing before and after. SpringPhysicsObject class (see Figure 13-12) can help you achieve this. It calculates the position of a fixed-quality object, which is connected to a spring with a definite elastic coefficient. This position is up and down, but the speed is slowed down by a friction constant. Here we will use a large quality constant and a large friction constant. The result is that the pitch effect becomes slow and the effect becomes weak quickly. You don't want to let the car rebound wildly.


Figure 13-12

This helper class is directly used for the CarPhysics class. It initializes the CarMass constant, with a friction of 1.5 and an elastic coefficient of 120 (both of which have relatively high values ). The initial position of the virtual spring is set to 0 (the car is in normal state ):

/// <summary>/// Car pitch physics helper for a simple spring effect for/// accelerating, decelerating and crashing./// </summary>SpringPhysicsObject carPitchPhysics = new SpringPhysicsObject(  CarMass, 1.5f, 120, 0);

When the speed of the car changes, you need to update the position of the virtual spring. You can use the ChangePos auxiliary method:

carPitchPhysics.ChangePos(speedChange);

Finally, you can call the Simulate method based on the time of the current frame to Simulate the pitch effect. Then, during rendering, you can use the position value of this class to obtain the current pitch value:

// Handle pitch springcarPitchPhysics.Simulate(moveFactor);

The interesting part of the SpringPhysicsObject class is obviously the Simulate method. All other methods only set some values. To understand the elasticity formula, you must know the bounce force of the spring, which is obtained by using the law of Hu KE in F = ma.

Hook's law reveals that the shape variable is proportional to the pressure. In this way, the elasticity, spring, stress, and strain physics can be described.

If you want to read more about Hu Ke's law, read a good formula book or read the internet. Wikipedia and Wolfram Research (http://scienceworld.wolfram.com) have good articles on physical issues.

You only use the simple elastic formula F =-kx. In this formula, F is the recovery force of the object connected to the spring, and k is the elastic coefficient. Figure 13-13 describes the formula and the effect of an Elastic object that changes over time. You will also use this effect on the pitch of a car.

If no force is applied to an object, the object remains at its initial position (0 ). But if you pull down the spring, the spring will stretch and stretch to restore the object to its initial position. When it returns to the initial position 0 again, the elasticity also returns to zero, but the object is still very fast, the object is still moving up. The reply force reversely blocks the object from moving up and eventually reaches its highest position 1. Now the bounce force is-1 and the object is pushed down again. When the object reaches the lowest point, it starts to reciprocating.

The force to slow down is friction. To ensure that the car does not rebound too much, the friction is very high. Please note that gravity is ignored here, because gravity is processed by the car itself, and gravity is ignored, which has little impact on the pitching effect of the car. In addition, pulling an object from the same direction does not affect the calculation, therefore, you can safely ignore the force effect.

The code in the Simulate method makes it work. With the knowledge you just gained, you should be able to quickly understand the code:

/// <summary>/// Simulate spring formular using the timeChange./// The velocity is increased by the timeChange * force / mass,/// the position is then timeChange * velocity./// </summary>public void Simulate(float timeChange){  // Calculate force again  force += -pos * springConstant;  // Calculate velocity  velocity = force / mass;  // And apply it to the current position  pos += timeChange * velocity;  // Apply friction  force *= 1.0f - (timeChange * friction);} // Simulate(timeChange)

The SpringPhysicsObject class can be found in the Game Physics namespace (see Figure 13-13 ). If you want to add more physical classes and implement more physical behaviors, you should implement them in this namespace. It is easier to reuse these physical effects in future projects. You only need to copy and use the physics namespace.


Figure 13-13

Collision Detection

The final task of this chapter completes the collision detection of vehicles and guardrails. Because you are the only car on the road, so the car does not collide with any vehicles, I am sure there are no other objects on the road can collision. If you allow collision with other objects on the road, collision detection and response will be much more complicated. For example, a collision with lights, signs, and garbage bins on the road means that if you hit them, they will be unlocked. These objects must collide with each other and interact with the world around them.

If you have a good physical engine, this can be achieved, but adjusting these objects requires a lot of work, you need to adjust the basic physical constants, and constantly test all different types of collisions. It may be interesting to implement this technology and adjust it, but there is no mature physical engine on XNA, even if the basic startup and running of it may take longer than the entire project.

The rules for collision detection and response are still the same, but you can simplify it as needed, involving only the collision of cars and guardrails. Because the guardrail cannot be damaged, the only impact of the collision is your car.

The biggest part of the physical performance of the Rocket Commander game is the collision detection and optimization between the minor planets. With the help of many unit detection, the collision response is not very complex, and basic collision detection can also be implemented in a very simple way.

PhysicsAsteroidManager

For example, the physicsasteroidphysicssmallscene class in the TestAsteroidPhysicsSmallScene unit test in the Rocket Commander game shows a good method for collision detection. This unit test allows you to test a variety of situations by pressing keys 1-7 and display the results of the minor collision event.

Figure 1314-14 shows the unit test, which uses two minor planets of the same size to fly to the other side and bounce back in the opposite direction after the collision. The SetupScene method is used to set the initial position of the minor, while unit testing processes all collision detection.


Figure 13-14

case 2:  // Collide with crazy movement vectors  AddAsteroid(new Vector3(-35, +19, 8) * (-2),    12.5f, asteroidModel.ObjectSize,    new Vector3(-35, +19, 8));  AddAsteroid(new Vector3(+15, 40, 14) * (-2),    12.5f, asteroidModel.ObjectSize,    new Vector3(+15, 40, 14));  break;

The TestAsteroidPhysicsSmallScene unit test calls the HandleSectorPhysics method to check all the minor planets in a specific region. If they are too close to each other, perform a simple ball surround test and handle collision events.

This method checks not only the minor in the region, but also all the minor in the surrounding area. Even with very good regional optimization, thousands of collision detection is still performed per frame in the Rocket Commander game, and it becomes slower if there are more planets. For this reason, Rocket Commander XNA uses multithreading technology to process physical and rendering code in two different threads.

The radius of the minor is added to the collision detection to check whether they are smaller than the physical size. If so, a collision occurs. The following code shows collision detection for a single region. The code for testing the surrounding area is similar, but it looks much longer.

// Only check this sector! Crosscheck with any other asteroid in// this sector.foreach (Asteroid otherAsteroid in thisSectorAsteroids)  if (asteroid != otherAsteroid)  {    float maxAllowedDistance =      otherAsteroid.collisionRadius +      asteroid.collisionRadius;  // Distance smaller than max. allowed distance?  if ((otherAsteroid.position     asteroid.position).LengthSq() <    maxAllowedDistance * maxAllowedDistance)  {    HandleAsteroidCollision(asteroid, otherAsteroid);  } // if (otherAsteroid.position)} // foreach if (asteroid)

Now the HandleAsteroidCollision method is used to handle collisions and keep the two sides away from each other:

// Put both circles outside of the collision// Add 1% to add a little distance between collided objects!otherAsteroid.position = middle +  otherPositionRel * otherAsteroid.collisionRadius * 1.015f;asteroid.position = middle +  positionRel * asteroid.collisionRadius * 1.015f;

Then, the method applies the total collision force to the mass of the minor, which reverses the motion vectors of the two minor planets to keep them away from the collision plane (purple lines in Figure 13-14 ). In this way, a smaller minor is pushed away by a larger minor with greater power. Taking a look at the unit test, this method is very long and has done a lot of additional checks to calculate the quality and direction of the Travel Star and add the rotation speed of the Minor Planet. However, the basic code for collision processing is as follows:

// Normalize movementVector3 asteroidDirection = asteroid.movement;asteroidDirection.Normalize();Vector3 otherAsteroidDirection = otherAsteroid.movement;otherAsteroidDirection.Normalize();// Get collision strength (1 if pointing in same direction,// 0 if 90 degrees) for both asteroids.float asteroidCollisionStrength = Math.Abs(Vector3.Dot(  asteroidDirection, asteroidNormal));float otherAsteroidCollisionStrength = Math.Abs(Vector3.Dot(  otherAsteroidDirection, otherAsteroidNormal));// Calculate reflection vectors from the asteroid direction and the// normal towards the reflection plane.Vector3 asteroidReflection =  ReflectVector(asteroidDirection, asteroidNormal);Vector3 otherAsteroidReflection =  ReflectVector(otherAsteroidDirection, otherAsteroidNormal);// Make sure the strength is calculated correctly// We have also to correct the reflection vector if the length was 0,// use the normal vector instead.if (asteroidDirection.Length() <= 0.01f){  asteroidCollisionStrength = otherAsteroidCollisionStrength;  asteroidReflection = asteroidNormal;} // if (asteroidDirection.Length)if (otherAsteroidDirection.Length() <= 0.01f){  otherAsteroidCollisionStrength = asteroidCollisionStrength;  otherAsteroidReflection = otherAsteroidNormal;} // if (otherAsteroidDirection.Length)// Ok, now the complicated part, everything above was really easy!asteroid.movement = asteroidReflection *  // So, first we have to reflect our current movement speed.  // This will be scaled to 1-strength to only account the reflection  // amount (imagine a collision with a static wall). In most cases  // Strength is close to 1 and this reflection will be very small.  ((1 - asteroidCollisionStrength) * asteroidSpeed +  // And finally we have to add the impuls, which is calculated  // by the formula ((m1-m2)*v1 + 2*m2*v2)/(m1+m2), see  // http://de.wikipedia.org/wiki/Sto%C3%9F_%28Physik%29 for more help.  (asteroidCollisionStrength *  (Math.Abs(asteroidMass - otherAsteroidMass) * asteroidSpeed +  (2 * otherAsteroidMass * otherAsteroidSpeed)) / bothMasses));  // Same for other asteroid, just with asteroid and otherAsteroid  // inverted.  otherAsteroid.movement = otherAsteroidReflection *    // Same as above.    ((1 - otherAsteroidCollisionStrength) * otherAsteroidSpeed +   (otherAsteroidCollisionStrength *   (Math.Abs(otherAsteroidMass - asteroidMass) * otherAsteroidSpeed +   (2 * asteroidMass * asteroidSpeed)) / bothMasses));

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.