-= The big book of usefull stuff for programmers =- Compiled by: Twisted Matrix (Homie_dont_play_dat@Yahoo.com) version: 1.00a Simple Physics ------------------------------ --------------------------------------------- By: Unknown --------------------------------------------- Trajectories (Parabolic Motion) Y = (vy*(x/vx)) - (.5*g*(x/vx)*(x/vx)) xv = initial velocity in the X direction yv = initial velocity in the Y direction g = gravity --------------------------------------------- By: Unknown --------------------------------------------- Vehicle Simulation Skidding if (v*v > f*g*r) wheel skids (goes straight) v = velocity f = friction g = gravity r = bend radius --------------------------------------------- By: Imagine_that --------------------------------------------- this is how you calculate how far to move the camera to maintain same orientation to a rotating object. leg = 2(rad*sin(deltA/2)) deltZ = leg(sin(deltA/2)) deltX = leg(cos(deltA/2)) leg = the leg of the triangle/ hyp. of there triangle rad = radius (distance between camera and object desired DeltA= change in angle of object turn DeltZ= change in camera z position DeltX= change in camera x position All you need to know is the rad and deltA the rest is calculated. All this is based off X,Y,Z coordinates and may need some further looking into for positive and negative movement. --------------------------------------------- By: Twisted Matrix ---------------------------------------------  Calculating distace between 2 points Dist#= sqrt((abs(x1#-x2#)*abs(x1#-x2#))+(abs(y1#-y2#)*abs(y1#-y2#))+(abs(z1#-z2#)*abs(z1#-z2#))) --------------------------------------------- By: Rottbott --------------------------------------------- REM Gets angle between two objects FUNCTION GetAngle(a, b) XDist# = OBJECT POSITION X(a) - OBJECT POSITION X(b) ZDist# = OBJECT POSITION Z(a) - OBJECT POSITION Z(b) Angle# = WRAPVALUE(ATANFULL(XDist#, ZDist#)) ENDFUNCTION Angle# Complex Physics --------------------------- -------------------------------------------- The physics of weight transfer as it applies to cars. *Usefull for if your making a racing or demolition game* By: Brian Beckman -------------------------------------------- Balancing a car is controlling weight transfer using throttle, brakes, and steering. This article explains the physics of weight transfer. You will often hear instructors and drivers say that applying the brakes shifts weight to the front of a car and can induce oversteer. Likewise, accelerating shifts weight to the rear, inducing understeer, and cornering shifts weight to the opposite side, unloading the inside tires. But why does weight shift during these maneuvers? How can weight shift when everything is in the car bolted in and strapped down? Briefly, the reason is that inertia acts through the center of gravity (CG) of the car, which is above the ground, but adhesive forces act at ground level through the tire contact patches. The effects of weight transfer are proportional to the height of the CG off the ground. A flatter car, one with a lower CG, handles better and quicker because weight transfer is not so drastic as it is in a high car. The rest of this article explains how inertia and adhesive forces give rise to weight transfer through Newton's laws. The article begins with the elements and works up to some simple equations that you can use to calculate weight transfer in any car knowing only the wheelbase, the height of the CG, the static weight distribution, and the track, or distance between the tires across the car. These numbers are reported in shop manuals and most journalistic reviews of cars. Most people remember Newton's laws from school physics. These are fundamental laws that apply to all large things in the universe, such as cars. In the context of our racing application, they are: The first law: {\bf a car in straight-line motion at a constant speed will keep such motion until acted on by an external force}. The only reason a car in neutral will not coast forever is that friction, an external force, gradually slows the car down. Friction comes from the tires on the ground and the air flowing over the car. The tendency of a car to keep moving the way it is moving is the inertia of the car, and this tendency is concentrated at the CG point. The second law: {\bf When a force is applied to a car, the change in motion is proportional to the force divided by the mass of the car}. This law is expressed by the famous equation \mbox{$F=ma$}, where $F$ is a force, $m$ is the mass of the car, and $a$ is the acceleration, or change in motion, of the car. A larger force causes quicker changes in motion, and a heavier car reacts more slowly to forces. Newton's second law explains why quick cars are powerful and lightweight. The more $F$ and the less $m$ you have, the more $a$ you can get. The third law: {\bf Every force on a car by another object, such as the ground, is matched by an equal and opposite force on the object by the car}. When you apply the brakes, you cause the tires to push forward against the ground, and the ground pushes back. As long as the tires stay on the car, the ground pushing on them slows the car down. Let us continue analyzing braking. Weight transfer during accelerating and cornering are mere variations on the theme. We won't consider subtleties such as suspension and tire deflection yet. These effects are very important, but secondary. The figure shows a car and the forces on it during a \mbox{one g''} braking maneuver. One g means that the total braking force equals the weight of the car, say, in pounds. In this figure, the black and white pie plate'' in the center is the CG. $G$ is the force of gravity that pulls the car toward the center of the Earth. This is the weight of the car; weight is just another word for the force of gravity. It is a fact of Nature, only fully explained by Albert Einstein, that gravitational forces act through the CG of an object, just like inertia. This fact can be explained at deeper levels, but such an explanation would take us too far off the subject of weight transfer. $L_f$ is the lift force exerted by the ground on the front tire, and $L_r$ is the lift force on the rear tire. These lift forces are as real as the ones that keep an airplane in the air, and they keep the car from falling through the ground to the center of the Earth. We don't often notice the forces that the ground exerts on objects because they are so ordinary, but they are at the essence of car dynamics. The reason is that the magnitude of these forces determine the ability of a tire to stick, and imbalances between the front and rear lift forces account for understeer and oversteer. The figure only shows forces on the car, not forces on the ground and the CG of the Earth. Newton's third law requires that these equal and opposite forces exist, but we are only concerned about how the ground and the Earth's gravity affect the car. If the car were standing still or coasting, and its weight distribution were 50-50, then $L_f$ would be the same as $L_r$. It is always the case that $L_f$ plus $L_r$ equals $G$, the weight of the car. Why? Because of Newton's first law. The car is not changing its motion in the vertical direction, at least as long as it doesn't get airborne, so the total sum of all forces in the vertical direction must be zero. $G$ points down and counteracts the sum of $L_f$ and $L_r$, which point up. Braking causes $L_f$ to be greater than $L_r$. Literally, the rear end gets light,'' as one often hears racers say. Consider the front and rear braking forces, $B_f$ and $B_r$, in the diagram. They push backwards on the tires, which push on the wheels, which push on the suspension parts, which push on the rest of the car, slowing it down. But these forces are acting at ground level, not at the level of the CG. The braking forces are indirectly slowing down the car by pushing at ground level, while the inertia of the car is trying' to keep it moving forward as a unit at the CG level. The braking forces create a rotating tendency, or torque, about the CG. Imagine pulling a table cloth out from under some glasses and candelabra. These objects would have a tendency to tip or rotate over, and the tendency is greater for taller objects and is greater the harder you pull on the cloth. The rotational tendency of a car under braking is due to identical physics. The braking torque acts in such a way as to put the car up on its nose. Since the car does not actually go up on its nose (we hope), some other forces must be counteracting that tendency, by Newton's first law. $G$ cannot be doing it since it passes right through the cetner of gravity. The only forces that can counteract that tendency are the lift forces, and the only way they can do so is for $L_f$ to become greater than $L_r$. Literally, the ground pushes up harder on the front tires during braking to try to keep the car from tipping forward. By how much does $L_f$ exceed $L_r$? The braking torque is proportional to the sum of the braking forces and to the height of the CG. Let's say that height is 20 inches. The counterbalancing torque resisting the braking torque is proportional to $L_f$ and half the wheelbase (in a car with 50-50 weight distribution), minus $L_r$ times half the wheelbase since $L_r$ is helping the braking forces upend the car. $L_f$ has a lot of work to do: it must resist the torques of both the braking forces and the lift on the rear tires. Let's say the wheelbase is 100 inches. Since we are braking at one g, the braking forces equal $G$, say, 3200 pounds. All this is summarized in the following equations: ${\rm 3200\:lbs\ times\ 20\:inches} = L_f {\rm \ times\ 50\: inches} - L_r {\rm \ times\ 50\: inches}$ $L_f + L_r = 3200\:{\rm lbs\ (this\ is\ always\ true)}$ With the help of a little algebra, we can find out that $L_f = 1600 + 3200 / 5 = 2240\: {\rm lbs}$ $L_r = 1600 - 3200 / 5 = 960 \: {\rm lbs}$ Thus, by braking at one g in our example car, we add 640 pounds of load to the front tires and take 640 pounds off the rears! This is very pronounced weight transfer. By doing a similar analysis for a more general car with CG height of $h$, wheelbase $w$, weight $G$, static weight distribution $d$ expressed as a fraction of weight in the front, and braking with force $B$, we can show that $L_f = dG + Bh / w$ $L_r = (1 - d)G - Bh / w$ These equations can be used to calculate weight transfer during acceleration by treating acceleration force as negative braking force. If you have acceleration figures in gees, say from a {\em G-analyst} or other device, just multiply them by the weight of the car to get acceleration forces (Newton's second law!). Weight transfer during cornering can be analyzed in a similar way, where the track of the car replaces the wheelbase and $d$ is always 50\% (unless you account for the weight of the driver). Those of you with science or engineering backgrounds may enjoy deriving these equations for yourselves. The equations for a car doing a combination of braking and cornering, as in a trail braking maneuver, are much more complicated and require some mathematical tricks to derive. Now you know why weight transfer happens. The next topic that comes to mind is the physics of tire adhesion, which explains how weight transfer can lead to understeer and oversteer conditions. in motion, and a heavier car reacts more slowly to forces. Newton's second law explains why quick cars are powerful and lightweight. The more $F$ and the less $m$ you have, the more $a$ you can get. -------------------------------------------- The physics of what causes tires to stay stuck and what causes them to break away and slide. *Usefull for if your making a racing game* By: Brian Beckman -------------------------------------------- In last month's article, we explained the physics behind weight transfer. That is, we explained why braking shifts weight to the front of the car, accelerating shifts weight to the rear, and cornering shifts weight to the outside of a curve. Weight transfer is a side-effect of the tires keeping the car from flipping over during maneuvers. We found out that a one $G$ braking maneuver in our 3200 pound example car causes 640 pounds to transfer from the rear tires to the front tires. The explanations were given directly in terms of Newton's fundamental laws of Nature. This month, we investigate what causes tires to stay stuck and what causes them to break away and slide. We will find out that you can make a tire slide either by pushing too hard on it or by causing weight to transfer off the tire by your control inputs of throttle, brakes, and steering. Conversely, you can cause a sliding tire to stick again by pushing less hard on it or by tranferring weight to it. The rest of this article explains all this in term of (you guessed it) physics. This knowledge, coupled with a good instinct' for weight transfer, can help a driver predict the consequences of all his or her actions and develop good instincts for staying out of trouble, getting out of trouble when it comes, and driving consistently at ten tenths. It is said of Tazio Nuvolari, one of the greatest racing drivers ever, that he knew at all times while driving the weight on each of the four tires to within a few pounds. He could think, while driving, how the loads would change if he lifted off the throttle or turned the wheel a little more, for example. His knowledge of the physics of racing enabled him to make tiny, accurate adjustments to suit every circumstance, and perhaps to make these adjustments better than his competitors. Of course, he had a very fast brain and phenomenal reflexes, too. I am going to ask you to do a few physics lab'' experiments with me to investigate tire adhesion. You can actually do them, or you can just follow along in your imagination. First, get a tire and wheel off your car. If you are a serious autocrosser, you probably have a few loose sets in your garage. You can do the experiments with a heavy box or some object that is easier to handle than a tire, but the numbers you get won't apply directly to tires, although the principles we investigate will apply. Weigh yourself both holding the wheel and not holding it on a bathroom scale. The difference is the weight of the tire and wheel assembly. In my case, it is 50 pounds (it would be a lot less if I had those \$3000 Jongbloed wheels! Any sponsors reading?). Now put the wheel on the ground or on a table and push sideways with your hand against the tire until it slides. When you push it, push down low near the point where the tire touches the ground so it doesn't tip over. The question is, how hard did you have to push to make the tire slide? You can find out by putting the bathroom scale between your hand and the tire when you push. This procedure doesn't give a very accurate reading of the force you need to make the tire slide, but it gives a rough estimate. In my case, on the concrete walkway in front of my house, I had to push with 85 pounds of force (my neighbors don't bother staring at me any more; they're used to my strange antics). On my linoleum kitchen floor, I only had to push with 60 pounds (but my wife does stare at me when I do this stuff in the house). What do these numbers mean? They mean that, on concrete, my tire gave me$85/50 = 1.70$gees of sideways resistance before sliding. On a linoleum race course (ahem!), I would only be able to get$60/50 = 1.20 G$. We have directly experienced the physics of grip with our bare hands. The fact that the tire resists sliding, up to a point, is called the {\em grip phenomenon}. If you could view the interface between the ground and the tire with a microscope, you would see complex interactions between long-chain rubber molecules bending, stretching, and locking into concrete molecules creating the grip. Tire researchers look into the detailed workings of tires at these levels of detail. Now, I'm not getting too excited about being able to achieve$1.70 G$cornering in an autocross. Before I performed this experiment, I frankly expected to see a number below$1 G$. This rather unbelievable number of$1.70 G$would certainly not be attainable under driving conditions, but is still a testimony to the rather unbelievable state of tire technology nowadays. Thirty years ago, engineers believed that one$G$was theoretically impossible from a tire. This had all kinds of consequences. It implied, for example, that dragsters could not possibly go faster than 200 miles per hour in a quarter mile: you can go$\sqrt{2ax} = 198.48\:{\rm mph}$if you can keep$1 G$acceleration all the way down the track. Nowadays, drag racing safety watchdogs are working hard to keep the cars under 300 mph; top fuel dragsters launch at more than 3 gees. For the second experiment, try weighing down your tire with some ballast. I used a couple of dumbells slung through the center of the wheel with rope to give me a total weight of 90 pounds. Now, I had to push with 150 pounds of force to move the tire sideways on concrete. Still about$1.70 G$. We observe the fundamental law of adhesion: the force required to slide a tire is proportional to the weight supported by the tire. When your tire is on the car, weighed down with the car, you cannot push it sideways simply because you can't push hard enough. The force required to slide a tire is called the {\em adhesive limit\/} of the tire, or sometimes the {\em stiction}, which is a slang combination of stick'' and friction.'' This law, in mathematical form, is $F \leq \mu W$ where$F$is the force with which the tire resists sliding;$\mu$is the {\em coefficient of static friction\/} or {\em coefficient of adhesion}; and$W$is the weight or vertical load on the tire contact patch. Both$F$and$W$have the units of force (remember that weight is the force of gravity), so$\mu$is just a number, a proportionality constant. This equation states that the sideways force a tire can withstand before sliding is less than or equal to$\mu$times$W$. Thus,$\mu W$is the maximum sideways force the tire can withstand and is equal to the stiction. We often like to speak of the sideways acceleration the car can achieve, and we can convert the stiction force into acceleration in gees by dividing by$W$, the weight of the car.$\mu$can thus be measured in gees. The coefficient of static friction is not exactly a constant. Under driving conditions, many effects come into play that reduce the stiction of a good autocross tire to somewhere around$1.10 G$. These effects are deflection of the tire, suspension movement, temperature, inflation pressure, and so on. But the proportionality law still holds reasonably true under these conditions. Now you can see that if you are cornering, braking, or accelerating at the limit, which means at the adhesive limit of the tires, any weight transfer will cause the tires unloaded by the weight transfer to pass from sticking into sliding. Actually, the transition from sticking mode' to sliding mode should not be very abrupt in a well-designed tire. When one speaks of a forgiving'' tire, one means a tire that breaks away slowly as it gets more and more force or less and less weight, giving the driver time to correct. Old, hard tires are, generally speaking, less forgiving than new, soft tires. Low-profile tires are less forgiving than high-profile tires. Slicks are less forgiving than DOT tires. But these are very broad generalities and tires must be judged individually, usually by getting some word-of-mouth recommendations or just by trying them out in an autocross. Some tires are so unforgiving that they break away virtually without warning, leading to driver dramatics usually resulting in a spin. Forgiving tires are much easier to control and much more fun to drive with. Driving by the seat of your pants'' means sensing the slight changes in cornering, braking, and acceleration forces that signal that one or more tires are about to slide. You can sense these change literally in your seat, but you can also feel changes in steering resistance and in the sounds the tires make. Generally, tires squeak' when they are nearing the limit, squeal' at the limit, and squall' over the limit. I find tire sounds very informative and always listen to them while driving. So, to keep your tires stuck to the ground, be aware that accelerating gives the front tires less stiction and the rear tires more, that braking gives the front tire more stiction and the rear tires less, and that cornering gives the inside tires less stiction and the outside tires more. These facts are due to the combination of weight transfer and the grip phenomenon. Finally, drive smoothly, that is, translate your awareness into gentle control inputs that always keep appropriate tires stuck at the right times. This is the essential knowledge required for car control, and, of course, is much easier said than done. Later articles will use the knowledge we have accumulated so far to explain understeer, oversteer, and chassis set-up. -------------------------------------------- The Basic calculations. *Usefull for if your making a racing game* By: Brian Beckman -------------------------------------------- In the last two articles, we plunged right into some relatively complex issues, namely weight transfer and tire adhesion. This month, we regroup and review some of the basic units and dimensions needed to do dynamical calculations. Eventually, we can work up to equations sufficient for a full-blown computer simulation of car dynamics. The equations can then be doctored' so that the computer simulation will run fast enough to be the core of an autocross computer game. Eventually, we might direct this series of articles to show how to build such a game in a typical microcomputer programming language such as C or BASIC, or perhaps even my personal favorite, LISP. All of this is in keeping with the spirit of the series, the Physics of Racing, because so much of physics today involves computing. Software design and programming are essential skills of the modern physicist, so much so that many of us become involved in computing full time. Physics is the science of measurement. Perhaps you have heard of highly abstract branches of physics such as quantum mechanics and relativity, in which exotic mathematics is in the forefront. But when theories are taken to the laboratory (or the race course) for testing, all the mathematics must boil down to quantities that can be measured. In racing, the fundamental quantities are distance, time, and mass. This month, we will review basic equations that will enable you to do quick calculations in your head while cooling off between runs. It is very valuable to develop a skill for estimating quantities quickly, and I will show you how. Equations that don't involve mass are called {\em kinematic}. The first kinematic equation relates speed, time, and distance. If a car is moving at a constant speed or velocity,$v$, then the distance$d$it travels in time$t$is $d = v t$ or velocity times time. This equation really expresses nothing more than the definition of velocity. If we are to do mental calculations, the first hurdle we must jump comes from the fact that we usually measure speed in miles per hour (mph), but distance in feet and time in seconds. So, we must modify our equation with a conversion factor, like this $d\:{\rm (feet)} = v \frac{{\rm miles}}{{\rm hour}}\:t\:{\rm (seconds)} \frac{5280\:{\rm feet / mile}}{3600\: {\rm seconds / hour}}$ % miles 5280 feet/mile % d(feet) = v ------- t(seconds) ----------------- % hour 3600 seconds/hour If you cancel out'' the units parts of this equation, you will see that you get feet on both the left and right hand sides, as is appropriate, since equality is required of any equation. The conversion factor is 5280/3600, which happens to equal 22/15. Let's do a few quick examples. How far does a car go in one second (remember, say, one-one-thousand, two-one-thousand,'' \etc\ to yourself to count off seconds)? At fifteen mph, we can see that we go $d = 15\:\mbox{{\rm mph times 1 sec times 22/15}} = \mbox{{\rm 22 feet}}$ or about 1 and a half car lengths for a 14 and 2/3 foot car like a late-model Corvette. So, at 30 mph, a second is three car lengths and at 60 mph it is six. If you lose an autocross by 1 second (and you'll be pretty good if you can do that with all the good drivers in our region), you're losing by somewhere between 3 and 6 car lengths! This is because the average speed in an autocross is between 30 and 60 mph. Everytime you plow a little or get a little sideways, just visualize your competition overtaking you by a car length or so. One of the reasons autocross is such a difficult sport, but also such a pure sport, from the driver's standpoint, is that you can't make up this time. If you blow a corner in a road race, you may have a few laps in which to make it up. But to win an autocross against good competition, you must drive nearly perfectly. The driver who makes the fewest mistakes usually wins! The next kinematic equation involves acceleration. It so happens that the distance covered by a car at constant acceleration from a standing start is given by $d = \frac{1}{2} a t^2$ or 1/2 times the acceleration times the time, squared. What conversions will help us do mental calculations with this equation? Usually, we like to measure acceleration in$G$s. One$G$happens to be 32.1 feet per second squared. Fortunately, we don't have to deal with miles and hours here, so our equation becomes, $d\:{\rm (feet)} = 16 a\:(G{\rm s})\:t\:{{\rm (seconds)}}^2$ % 2 % d(feet) = 16 a(Gs) t(seconds) % roughly. So, a car accelerating from a standing start at \mbox{$\frac{1}{2} G$}, which is a typical number for a good, stock sports car, will go 8 feet in 1 second. Not very far! However, this picks up rapidly. In two seconds, the car will go 32 feet, or over two car lengths. Just to prove to you that this isn't crazy, let's answer the question How long will it take a car accelerating at \mbox{$\frac{1}{2} G$} to do the quarter mile?'' We invert the equation above (recall your high school algebra), to get $t = \sqrt{d\:{\rm (feet)} \ 16 a\:(G{\rm s})}$ and we plug in the numbers: the quarter mile equals 1320 feet, \mbox{$a = \frac{1}{2} G$}, and we get$t = \sqrt{1320/8} = \sqrt{165}$which is about 13 seconds. Not too unreasonable! A real car will not be able to keep up full \mbox{$\frac{1}{2} G$} acceleration for a quarter mile due to air resistance and reduced torque in the higher gears. This explains why real (stock) sports cars do the quarter mile in 14 or 15 seconds. The more interesting result is the fact that it takes a full second to go the first 8 feet. So, we can see that the launch is critical in an autocross. With excessive wheelspin, which robs you of acceleration, you can lose a whole second right at the start. Just visualize your competition pulling 8 feet ahead instantly, and that margin grows because they are hooked up' better. For doing these mental calculations, it is helpful to memorize a few squares. 8 squared is 64, 10 squared is 100, 11 squared is 121, 12 squared is 144, 13 squared is 169, and so on. You can then estimate square roots in your head with acceptable precision. Finally, let's examine how engine torque becomes force at the drive wheels and finally acceleration. For this examination, we will need to know the mass of the car. Any equation in physics that involves mass is called {\em dynamic}, as opposed to kinematic. Let's say we have a Corvette that weighs 3200 pounds and produces 330 foot-pounds of torque at the crankshaft. The Corvette's automatic transmission has a first gear ratio of 3.06 (the auto is the trick set up for vettes---just ask Roger Johnson or Mark Thornton). A transmission is nothing but a set of circular, rotating levers, and the gear ratio is the leverage, multiplying the torque of the engine. So, at the output of the transmission, we have $3.06 \times 330 = 1010\:\mbox{{\rm foot-pounds}}$ of torque. The differential is a further lever-multiplier, in the case of the Corvette by a factor of 3.07, yielding 3100 foot pounds at the center of the rear wheels (this is a lot of torque!). The distance from the center of the wheel to the ground is about 13 inches, or 1.08 feet, so the maximum force that the engine can put to the ground in a rearward direction (causing the ground to push back forward---remember part 1 of this series!) in first gear is $3100\:\mbox{{\rm foot-pounds}} / 1.08\:{\rm feet} = 2870\:{\rm pounds}$ Now, at rest, the car has about 50/50 weight distribution, so there is about 1600 pounds of load on the rear tires. You will remember from last month's article on tire adhesion that the tires cannot respond with a forward force much greater than the weight that is on them, so they simply will spin if you stomp on the throttle, asking them to give you 2870 pounds of force. We can now see why it is important to squeeeeeeeze the throttle gently when launching. In the very first instant of a launch, your goal as a driver is to get the engine up to where it is pushing on the tire contact patch at about 1600 pounds. The tires will squeal or hiss just a little when you get this right. Not so coincidentally, this will give you a forward force of about 1600 pounds, for an$F = ma$(part 1) acceleration of about \mbox{$\frac{1}{2} G$}, or half the weight of the car. The main reason a car will accelerate with only \mbox{$\frac{1}{2} G$} to start with is that half of the weight is on the front wheels and is unavailable to increase the stiction of the rear, driving tires. Immediately, however, there will be some weight transfer to the rear. Remembering part 1 of this series again, you can estimate that about 320 pounds will be transferred to the rear immediately. You can now ask the tires to give you a little more, and you can gently push on the throttle. Within a second or so, you can be at full throttle, putting all that torque to work for a beautiful hole shot! In a rear drive car, weight transfer acts to make the driving wheels capable of withstanding greater forward loads. In a front drive car, weight transfer works against acceleration, so you have to be even more gentle on the throttle if you have a lot of power. An all-wheel drive car puts all the wheels to work delivering force to the ground and is theoretically the best. Technical people call this style of calculating back of the envelope,'' which is a somewhat picturesque reference to the habit we have of writing equations and numbers on any piece of paper that happens to be handy. You do it without calculators or slide rules or abacuses. You do it in the garage or the pits. It is not exactly precise, but gives you a rough idea, say within 10 or 20 percent, of the forces and accelerations at work. And now you know how to do back-of-the-envelope calculations, too. -------------------------------------------- Simulating Car Dynamics with a Computer Program *Usefull for if your making a racing game* By: Brian Beckman -------------------------------------------- This month, we begin writing a computer program to simulate the physics of racing. Such a program is quite an ambitious one. A simple racing video game, such as Pole Position,'' probably took an expert programmer several months to write. A big, realistic game like Hard Drivin'\,'' probably took three to five people more than a year to create. The point is that the topic of writing a racing simulation is one that we will have to revisit many times in these articles, assuming your patience holds out. There are many just physics' topics still to cover too, such as springs and dampers, transients, and thermodynamics. Your author hopes you will find the computer programming topic an enjoyable sideline and is interested, as always, in your feedback. We will use a computer programming language called Scheme. You have probably encountered BASIC, a language that is very common on personal computers. Scheme is like BASIC in that it is {\em interactive}. An interactive computer language is the right kind to use when inventing a program as you go along. Scheme is better than BASIC, however, because it is a good deal simpler and also more powerful and modern. Scheme is available for most PCs at very modest cost (MIT Press has published a book and diskette with Scheme for IBM compatibles for about \$40; I have a free version for Macintoshes). I will explain everything we need to know about Scheme as we go along. Although I assume little or no knowledge about computer programming on your part, we will ultimately learn some very advanced things. The first thing we need to do is create a {\em data structure\/} that contains the mathematical state of the car at any time. This data structure is a block of computer memory. As simulated time progresses, mathematical operations performed on the data structure simulate the physics. We create a new instance of this data structure by typing the following on the computer keyboard at the Scheme prompt: \begin{verbatim} (new-race-car) \end{verbatim} This is an example of an {\em expression}. The expression includes the parentheses. When it is typed in, it is {\tt evaluated} immediately. When we say that Scheme is an interactive programming language, we mean that it evaluates expressions immediately. Later on, I show how we {\em define\/} this expression. It is by defining such expressions that we write our simulation program. Everything in Scheme is an expression (that's why Scheme is simple). Every expression has a value. The value of the expression above is the new data structure itself. We need to give the new data structure a name so we can refer to it in later expressions: \begin{verbatim} (define car-161 (new-race-car)) \end{verbatim} This expression illustrates two Scheme features. The first is that expressions can contain sub-expressions inside them. The inside expressions are called {\em nested}. Scheme figures out which expressions are nested by counting parentheses. It is partly by nesting expressions that we build up the complexity needed to simulate racing. The second feature is the use of the special Scheme word {\tt define}. This causes the immediately following word to become a stand-in synonym for the value just after. The technical name for such a stand-in synonym is {\em variable}. Thus, the expression {\tt car-161}, wherever it appears after the {\tt define} expression, is a synonym for the data structure created by the nested expression {\tt (new-race-car)}. We will have another data structure (with the same format) for {\tt car-240}, another for {\tt car-70}, and so on. We get to choose these names to be almost anything we like \footnote{ It so happens, annoyingly, that we can't use the word {\tt car}. This is a Scheme reserved word, like {\tt define}. Its use is explained later}. So, we would create all the data structures for the cars in our simulation with expressions like the following: \begin{verbatim} (define car-161 (new-race-car)) (define car-240 (new-race-car)) (define car-70 (new-race-car)) \end{verbatim} The state of a race car consists of several numbers describing the physics of the car. First, there is the car's position. Imagine a map of the course. Every position on the map is denoted by a pair of coordinates, $x$ and $y$. For elevation changes, we add a height coordinate, $z$. The position of the center of gravity of a car at any time is denoted with expressions such as the following: \begin{verbatim} (race-car-x car-161) (race-car-y car-161) (race-car-z car-161) \end{verbatim} Each of these expressions performs {\em data retrieval\/} on the data structure {\tt car-161}. The value of the first expression is the $x$ coordinate of the car, \etc Normally, when running the Scheme interpreter, typing an expression simply causes its value to be printed, so we would see the car position coordinates printed out as we typed. We could also store these positions in another block of computer memory for further manipulations, or we could specify various mathematical operations to be performed on them. The next pieces of state information are the three components of the car's velocity. When the car is going in any direction on the course, we can ask how fast is it going in the $x$ direction, ignoring its motion in the $y$ and $z$ directions?'' Similarly, we want to know how fast it is going in the $y$ direction, ignoring the $x$ and $z$ directions, and so on. Decomposing an object's velocity into separate components along the principal coordinate directions is necessary for computation. The technique was originated by the French mathematician Descartes, and Newton found that the motion in each direction can be analyzed independently of the motions in the other directions at right angles to the first direction. The velocity of our race car is retrieved via the following expressions: \begin{verbatim} (race-car-vx car-161) (race-car-vy car-161) (race-car-vz car-161) \end{verbatim} To end this month's article, we show how velocity is computed. Suppose we retrieve the position of the car at simulated time $t_1$ and save it in some variables, as follows: \begin{verbatim} (define x1 (race-car-x car-161)) (define y1 (race-car-y car-161)) (define z1 (race-car-z car-161)) \end{verbatim} and again, at a slightly later instant of simulated time, $t_2$: \begin{verbatim} (define x2 (race-car-x car-161)) (define y2 (race-car-y car-161)) (define z2 (race-car-z car-161)) \end{verbatim} We have used {\tt define} to create some new variables that now have the values of the car's positions at two times. To calculate the average velocity of the car between the two times and store it in some more variables, we evaluate the following expressions: \begin{verbatim} (define vx (/ (- x2 x1) (- t2 t1))) (define vy (/ (- y2 y1) (- t2 t1))) (define vz (/ (- z2 z1) (- t2 t1))) \end{verbatim} The nesting of expressions is one level deeper than we have seen heretofore, but these expressions can be easily analyzed. Since they all have the same form, it suffices to explain just one of them. First of all, the {\tt define} operation works as before, just creating the variable {\tt vx} and assigning it the value of the following expression. This expression is \begin{verbatim} (/ (- x2 x1) (- t2 t1)) \end{verbatim} In normal mathematical notation, this expression would read $\frac{x_2 - x_1}{t_2 - t_1}$ and in most computer languages, it would look like this: \begin{verbatim} (x2 - x1) / (t2 - t1) \end{verbatim} We can immediately see this is the velocity in the $x$ direction: a change in position divided by the corresponding change in time. The Scheme version of this expression looks a little strange, but there is a good reason for it: consistency. Scheme requires that all operations, including everyday mathematical ones, appear in the first position in a parenthesized expression, immediately after the left parenthesis. Although consistency makes mathematical expressions look strange, the payback is simplicity: all expressions have the same form. If Scheme had one notation for mathematical expressions and another notation for non-mathematical expressions, like most computer languages, it would be more complicated. Incidentally, Scheme's notation is called Polish notation. Perhaps you have been exposed to Hewlett-Packard calculators, which use reverse Polish, in in which the operator always appears in the {\em last\/} position. Same idea, and advantages, as Scheme, only reversed. So, to analyze the expression completely, it is a division expression \begin{verbatim} (/ ...) \end{verbatim} whose two arguments are nested subtraction expressions \begin{verbatim} (- ...) (- ...) \end{verbatim} The whole expression has the form \begin{verbatim} (/ (- ...) (- ...)) \end{verbatim} which, when the variables are filled in, is \begin{verbatim} (/ (- x2 x1) (- t2 t1)) \end{verbatim} After a little practice, Scheme's style for mathematics becomes second nature and the advantages of consistent notation pay off in the long run. Finally, we should like to store the velocity values in our data structure. We do so as follows: \begin{verbatim} (set-race-car-vx! car-161 vx) (set-race-car-vy! car-161 vy) (set-race-car-vz! car-161 vz) \end{verbatim} The {\tt set} operations change the values in the data structure named {\tt car-161}. The exclamation point at the end of the names of these operations doesn't do anything special. It's just a Scheme idiom for operations that change data structures. -------------------------------------------- Intellegent behavior without real Artificial intellegence *Usefull for quake type enemies* By: Neil Kirby -------------------------------------------- Introduction This paper describes a way to give intelligent behavior to computer operated objects. It traces the evolutionary approach used in the "Auto" program of the "Bots" family of games. The Bots system is described to provide a context, and the results of each step in the evolution are discussed. While the changes made are particular to the Auto program, the method is applicable to other programs. The fundamentals of the method are: 1. Analyze good and bad behaviors. 2. Quantify parameters to new algorithms. 3. Apply constant evolutionary pressures by repeatedly testing. The method has proven to be quite successful. The Auto program has progressed from hopelessly poor play to well above average play skills without any formal AI methods. The Basic Approach The basic approach greatly resembles classical Darwinistic evolution. Start with simplistic behavior, however bad. Simple behavior is best described as whatever is easiest to code. Analyze the failures of the simple methods. If available, observe the differences between successful behavior, especially that of human players, and the failures of the computer players. The most difficult step is to identify the parameters that can be used to control successful behavior. Once this has been done, use regular code to allow the program to react to these parameters. The process is completed by repeatedly testing in play. The ease of fast, repeated play afforded by computerization accelerates the process. This approach is easily observed in the Auto program. The Bots Family of Games The Auto, Aero, and Bots programs make up the Bots family of multiplayer, tactical ground and air combat games. These run under the Unix System VTM operating system and are written entirely in the C programming language. Bots and Auto deal with futuristic ground combat units loosely comparable to tanks while Aero deals with flying futuristic aircraft. The Bots and Aero programs are used by human players and Auto is the computer managed equivalent to Bots. The Bots family of games supports but does not require team play. Since the Bots family are multiple player, multiple process games, events are performed simultaneously. A unit can find out the actions of other units only after committing its own actions. The events that make up a turn are motion, followed by active fire, and ending with passive fire. After every ten turns, repair and resupply are made available to a unit. The manner in which a unit conducts its motion and fire are strongly influenced by the construction of the unit. Building a Unit The units used in Bots and Auto are built according to the tastes of the player running them. A unit has six armor facings protecting its internal systems from damage. Armor is ablative; each point of damage reduces the amount of armor by one. Once a given armor facing is reduced to zero, all remaining damage is applied to the internal systems. There are a number of internal systems to protect: life support, control, chassis, reactor, batteries, hardpoints, weapons, and ammunition. Each has a cost and weight associated with it, forcing economic compromises to be made to build a unit to meet a given cost. The mobility of a unit is based on the amount of power available and the current mass of the unit, both of which can change in play. Weapons There are a variety of weapons systems available, each with different characteristics. Weapons that require ammunition usually need little power while power-based weapons require much more. The lasers are relatively light in mass, short-range, and power hungry. Mortars have a minimum range and require heavy ammunition, but they also have a long maximum range and do not require line of sight to fire. Autocannon inflict moderate damage to moderate ranges, but they too, require a large amount of moderately heavy ammunition. Miniguns are lighter, smaller, short-range versions of the autocannon. Missiles have varying ranges and warheads, but they can be shot down by point defenses, and they too, are heavy. Particle beam weapons are highly effective in a narrowly focused range. Aside from mortars, missiles, and particle beams, most weapons improve as range shortens. The non-offensive weapons systems are stealth, missile defense, and hardpoints. Stealth, which is expensive, allows a unit to approach others and remain unseen. Missile defense attempts to shoot down incoming missiles. Hardpoints are mounts for optional, single-shot items. The most common hardpoint load is a jump pack. Jump packs allow a unit to jump over obstacles such as water. They increase the mobility of a unit greatly but can only be used once. The other common hardpoint load is an anti- aircraft missile. Play Balance (Rock, Paper, Scissors) The selection of a weapon determines much about the unit. Units with long-range weapons usually require heavy ammunition. Their great weight means limited mobility. Limited mobility implies an inability to escape from units with high mobility and short-range weapons. It is axiomatic that short-range weapons require high mobility. Therefore, short-range weapons must be light to be effective. These trade-offs are required for play balance among a wide diversity of systems. Mortar units, for example, were popular on teams but few people actually wanted to play them. To be successful in play, a unit must maneuver effectively, fire its weapons, and evade enemy fire. It should distribute enemy fire across multiple armor facings. If team mates are present, a unit should coordinate fire among the team members to combine fire against single enemy units. If a unit takes damage, it should flee until it is repaired. The richness of detail in the Bots family of games is comparable to that of Star Fleet BattlesTM. Auto units are not allowed to cheat, so the behavior code cannot access information that a human player in the same situation would not have. The advantage of access to hidden data was considered at first, but has proven to be unnecessary. No Auto program was written for Aero units. The success of Auto units on the ground removed all demand for an Auto equivalent to Aero. The Original Algorithm The original algorithm for Autos was quite simple. The closest enemy unit was selected as the target. All other units were ignored. The Auto turned to face the enemy and attempted to close. (See Figure 1) After maneuvers were complete, the unit attempted to fire its weapons. The fire target was the closest enemy within the arc of the weapons fire. The unit would not flee if damaged. The unit would not jump unless blocked by water, buildings, or steep slopes. Spreading Out Damage There were many failures with the original algorithm. Foremost among these was the propensity for the unit to lose its center forward armor and take severe internal damage while the left and right forward armor facings were pristine. The solution to this problem was for the unit to shorten the amount it moved to save sufficient mobility to rotate after its motion. (See Figure 2) This rotation would bring the strongest forward armor to face the closest enemy unit. Relative bearing and the integer values of the forward armor were the parameters that enabled this change, which typically tripled the survival of all units. It especially allowed units with short-range weapons to close to their effective ranges. This algorithm became known as the basic closure code. Self Assessment The modified algorithm still had major problems. During a long closure, a unit would loose all three forward armor facings, continue closing, and take fatal internals. The fix involved self assessment. Before a unit started maneuvers, it would evaluate the state of its forward armor, internal systems, and ammunition. If all three forward armor facings were below minimum, half of any internal system was destroyed, or if ammunition was gone, then the unit would declare itself to be unfit for battle and flee. It would turn its strongest rear armor toward the closest enemy and move as far away as possible. This is just a slightly modified version of the basic closure code. If the unit had a jump pack available, it would jump as far away as possible. It would choose not to shoot power based weapons to save energy for mobility. The parameters for this change were simple integer numbers: armor, systems, and ammunition counts. This change increased the long term survivability of the Auto units greatly. After it, destroying a unit often required a long chase. In rolling terrain, enemy units would simply disappear when they were seriously damaged. Battle Range At this point, Auto units were interesting but not threatening. Their maneuvers were highly predictable. At point blank range a unit would close to zero range and stop. Since all motion in Bots is simultaneous, human players would simply move forward and turn around, finding themselves at near zero range facing the back of the Auto unit. Fatal internals for the Auto unit often soon followed. For long-range units such as mortars, and specific range units such as particle beam weapons, continuos closure was especially counter-productive. Mortar units have a minimum range requirement, and care very little about range otherwise. In the laser family, where closure improves damage, closure also gives the advantage to the lightest and shortest ranged lasers. The fix was to establish a battle range (known as BRG) for each weapon type. The parameter used with BRG was range. BRG numbers were tuned during play. While many weapons benefit from close range, BRG was picked to balance survivability and the ability to inflict damage. Long-range units would prefer to stay at range, denying short-range units any fire. If a unit found itself too close, it would back up as much as it could. Yet backing up costs twice as much as forward motion. BRG helped to keep the long-range support units out of trouble, and it helped all units survive combat with a short-range unit. Short-range units were still too predictable and easy for human players to destroy. BRG was the evolutionary step that set the stage for a major milestone in Auto evolution. The First Major Milestone Change: New Maneuver Code The problem with the maneuver code was predictability. The new maneuver code dealt with the answers to two questions: "Where can a unit go?" and "Where does a unit want to go?" The first question is answered by computing the mobility of a unit, which is based on its power and mass. The unit can get to roughly any point within a circle, centered on the unit, of radius equal to the mobility of the unit. When computing the radius of the mobility circle, sufficient mobility is deducted from the radius to provide for turns. The second question is answered by BRG. If the target does not move, the most effective place to be is some place on a circle, centered on the target, of radius BRG. (See Figure 3) If the two circles do not intersect, the existing basic closure code is used. If the circles intersect, there are three possibilities. The first possibility is shown in Figure 4. This is the most dangerous case for the target, and the best case for the attacker. This situation is most often seen when a high mobility unit carrying short ranged weapons attacks. The unit will pick a random point on the BRG circle, move to it, and turn to face the target. For the target to evade, it must either move far enough to get out of range, or it must move behind the random point on the BRG circle where the attacker will appear. Neither of these evasions is easy. The first requires good mobility, and the second requires good luck. If the target does move far enough away to deny weapons fire, the attacker will have more power available to move in the next turn. The second possibility is shown in Figure 5. This is a good case for any attacker. This situation is most often seen when a medium or high mobility unit carrying medium-range weapons attacks. The unit randomly picks one of the two intersection points, moves to it, and turns to face the target. Only a target with more mobility than the attacker will be able to out maneuver the attacker. As Figure 5 moves toward Figure 4, the attacker becomes nearly impossible to evade. The third case is shown in Figure 6. The mobility circle is inside the BRG circle, which means that the attacker is too close. This is usually the case when a low mobility unit carrying long-range weapons is closer than desired to an enemy unit. Here the unit determines if it would get farther away by backing up, or by turning away, moving forward, and turning again to face the target. It chooses the way that takes it farthest away and executes that maneuver. BRG and computed mobility, the parameters of the change, are combined in an effective algorithm. The effect of the first milestone change was dramatic. Attacking units were much more effective (fleeing units were unaffected). Human players could no longer destroy Auto units without pause. Close combat maneuvers became very dicey. Novice players had less than a 50% chance of winning a one-on-one duel. In single combat, Auto units played a solid, if uninspired, game and they never made stupid errors. Initial Team Play: Communications The team play of Autos still lacked a great deal - they fought as a mob, rather than as a team. Any unit that could see no targets would pick a random patrol point on the map and head toward it. This scattering behavior was good for finding hidden enemy units, but poor for fighting enemy teams. If one unit on a team was engaged, the rest of the team would ignore the combat unless they too could see the target. Evolution continued, as Auto units learned basic communications skills. A unit that could see no targets would ask its team for targeting information. The other units (Aero, Auto, and Bots) on the same team would reply with the map coordinates of the targets that they could see. These coordinates could be used the next turn to plot motion. Units that did not require line- of-sight to fire, such as mortars, would fire blindly on the map coordinates given. The effects of this change were two-fold. It allowed high mobility units carrying short-ranged weapons to close upon enemy units that they could not see. This meant that once an enemy unit was spotted, all unoccupied Autos would head toward it, even in rolling terrain. The second effect provided mortar teams with something productive to do. Communicating map coordinates proved to be an effective change. To the enemy units, it meant to expect mortar fire whenever spotted by any member of the Auto team. A particularly nasty combination was to be stalked by an unseen stealth unit that was broadcasting coordinates to its mortar teammates. This change tended to keep mobs of Autos together, but they still fought as a mob. The Second Major Milestone Change: Improved Team Play Targeting was still based on the closest enemy that could be fired at. In team play, a lone unit could distract part of a team of Autos and play Pied Piper while the rest of the Piper's team destroyed the other part of the Auto team. The Piper might not survive, but while it was being destroyed, multiple enemy units would be destroyed, tipping the battle against the Autos. The second milestone change increased team play. Team play was based on the concept of the team target. The enemy unit that appeared to be hurt the most would be designated as team target. This designation was based on the volume of fire an enemy had absorbed. The team target would always be the preferred target for motion control. If the team target was between the minimum and maximum effective range for the weapons fired, it would be the preferred target for fire as well. The results were often devastating and occasionally quite strange. The devastating part stemmed from the fact that a single unit, often already damaged, could now take all the mortar, long-range missile, autocannon, and much of the short-range laser fire that an entire team could inflict. The strange part would happen when an Auto unit would move directly past and ignore a closer target in order to help destroy the team target. But if the team target were not a viable target, each unit would fire as before, usually at the closest target. Mishaps in team play were now fatal. Teams of experts were now doing well to achieve a kill ratio of 2.5:1 in favor of the experts. Novice teams required two to five times numerical superiority to win. The parameters used had been developed in earlier stages of evolution. Attack Jumps Evolution continued as details were refined to solve minor problems. One problem was that Autos would only use a jump pack to flee or to cross water. This meant that they would often have an unused jump pack at reload time, when a new jump pack would be available. The fix was simple; units still carrying a jump pack that were near their reload time would be free to jump to increase their mobility. The parameter used was the unit's turn counter, which already existed. This change made it dangerous to rely on predictions about the mobility of an Auto unit. A fast moving unit that had been moving four ranges per turn would suddenly jump eight and move four more for a total of twelve ranges of motion when only four were expected. Dealing With Aeros The final changes involved dealing with Aeros. Bots and Autos usually move one to four ranges per turn. Aeros need to move at least ten to retain airspeed, and speeds of twenty to fifty are normal. Normal altitudes for Aeros typically run from eight to twenty ranges of altitude. The first problem Aeros created was that Autos would attempt to set up motion based on an Aero target. Since the motion algorithms are optimized for non-moving targets, using an Aero to set up motion was ineffective for units with a short BRG. It was ineffective for units with a long BRG if the Aero was close by, since the bearing of the Aero would change dramatically. Even if perfect predictive algorithms were available, only units with a long BRG have sufficient range to hurt Aeros at altitude. The important changes were range based. All units that had a BRG of 25 or higher would prefer any visible enemy Aero to all other targets for fire and motion. Units with lower BRG would ignore Aeros when plotting motion, but if an Aero was somehow in acceptable range, it would be the preferred fire target. At reload time, Autos remembered if they had seen any Aeros since last reload and changed their hardpoint weapons mix to prefer anti- aircraft missiles. The changes decreased the survivability of Aeros greatly. Aero targets were preferred even to team targets, often with the same deadly results. The much-maligned mortar units provided greatly needed flak fire. Other less popular long BRG units gained a new role. Also, the advent of the stealth anti-aircraft missile battery eased the problems ground units had with Aeros. Future Evolution There are still several deficiencies with the Auto program. Complex terrain tends to mystify Autos, especially urban terrain and bridges. An Auto unit will occasionally present weak or down armor toward one enemy while fighting another. This single mindedness also shows up when a damaged unit flees. Motion directly away from the closest enemy, which is always correct in one-on-one, can be fatal when intermixed with an enemy team. Observations About The Process Many observations are worth examining. The first of these is that the process of analysis and synthesis is regenerative. The initial BRG change set the stage for the first milestone change (maneuver code). BRG also led to min/max range, which when coupled with communications led to the second milestone change (team play). Some of the other analysis that went on made it possible and more probable that algorithms could be generated to improve poor behavior. Not as obvious in the paper is the fact that intensive testing helps drive the process. The entire evolutionary cycle mentioned above took place at lunchtimes over the course of a year. The testing allowed the author to observe human behavior in order to model it, and it clearly showed any deficiencies in the algorithms. One very hopeful point is that simple methods often suffice. The long closure code and the code for flight is simple but has proven to be very effective. The early code, which had numerous deficiencies, was still interesting and fun. Between the first and second milestone changes, there was, occasionally, the semblance of team behavior by default. If a given enemy unit was the best or only target available to a team, the entire team fired upon it. In rolling terrain this would be fatal as one unit encountered groups of enemy units. A final point is that the code is well behaved. It is small, runs rapidly, and is easy to follow. The behavior control parts of the code do not require any extensive calculations. The code is short, with only two files. In fact, the Auto program has less source and a smaller executable than the Bots program. The increase in size from automation is more than offset by the reduction in size gained by deleting the user interface. The control flow of the code is relatively easy to follow, and therefore easy to modify. Conclusions: The evolutionary method is a viable alternative to exploring AI methodologies. The method is universally available to programmers who have sufficient time for repeated testing. It is well suited to game programs in which the computer and human players deal with the same objects and information - - the programmer can model computer behavior on successful human behavior. The method fails when the programmer cannot identify the keys to changing poor behavior and the default simple methods are ineffective. For the multiplayer, tactical combat games that this author has written, the methods have produced effective code that is fast, compact, and often pleasingly simple.