This tutorial will show you how to implement the Lagrange formalism of mechanics into your programs, and explain what situations it might be useful in.
IntroThe first introduction that people are usually given to physics uses Newton's laws to derive equations of motion for particles. These equations are simple to understand and use, however, for more complex problems, it can sometimes be difficult to find the equations of motion using this formalism. Instead, we can turn to two newer formulations of physics, the Hamiltonian and Lagrangian. These formulations are so powerful, in fact, that they can even be applied to situations where Newton's laws would typically be completely useless, like quantum mechanics and relativity (although some difficulties do arise with relativistic Hamiltonians).
Although the latter two cases are almost certain never to come up in game physics, there are many other times when the Lagrangian and Hamiltonian may come in useful. I'm not aware of any specific cases relating to game programming, however, I did notice that the use of the Lagrangian was mentioned in a book on game physics that I briefly looked at, so whatever the applications are, I figure they must exist. I will try to give a few examples of where it might be better to use the Lagrangian, but they may or may not be relevant to most games.
Even outside of physics, there may be some kind of application of the Lagrangian formalism to AI. I'm not very familiar with A* algorithms, since AI isn't an area I've studied very intensively, but I do know that they revolve around minimizing some kind of path. The Lagrangian makes use of the calculus of variations to do something similar - to find the path that minimizes T - U, so insight into this method of calculation may also lend some insight to people interested in A*.
Part I: Background Physics Information - Forces and PotentialsThere's more than one way of deriving Lagrangian mechanics, and not all of them directly involve the calculus of variations to minimize the action (T-U), but unfortunately, that is the only derivation that I can remember. The derivation that I'm going to present is the standard derivation, and I doubt that other derivations could have significantly different interpretations. The idea of path minimization is very important in physics as well as other areas, so before I get into any math, I think it warrants further explanation as to what exactly is going on.
In physics, we have things called force fields. They're not quite the same as the ones you see on star trek that knock you over when you run into them, like hitting a brick wall. Instead, they're a collection of vectors in space that cause objects in them to move around. When an object is in the force field, it will accellerate, accellerating in the direction that the little vector in space is pointing, by an amount equal to that vector's length.
Gravity, for example, is a force field. Objects in a gravitational field accellerate toward the body giving off the gravitational force. In the case of the earth, we can look at the space around the earth as being filled with lots of little vectors, pointing toward the surface of the earth that get smaller by a factor of 1/r^2 (where r is the distance from the center of the earth).
Of course, there are other forces as well, namely the electromagnetic force, the strong nuclear force, and the weak nuclear force. The principle is the same for these forces, except that all objects won't accellerate equally in them. The force on the objects gets multiplied by some value, like charge.
This is a very good description of mechanics in general, that forces act on objects making them move. In some sense, we can say that forces are real things that actually inhabit points in space.
However, we can define something else whose reality is slightly less definite - something that we can't actually say is a real, physical thing, like force, but which is just as useful in physics. It's called a potential.
To lift something up in a gravitational field, or any field that actually acts on the body, it requires a certain amount of work. The amount of work required is dependant on the mass (or charge, as in the case of an electric field) of the object and the strength of the force field. From now on, I'm only going to talk about gravitational fields, as they are the most relevant, and it will do away with other complications that may arise as in the case of the magnetic field (as well as getting rid of the need to mention charge).
The amount of work required to lift an object can simply be calculated from the method we use to calculate work:
Work = Integral(F*dx)F is the force acting on the object, which is the gravitational field multiplied by the mass, and dx is an infintesimal component of the path.
The meaning of that equation might seem a little bit hard to decipher to some people at first. But all it's really telling us is that the work done on an object is equal to the force on the object multiplied by the distance over which that force is applied. Since the actual values of force and the direction/speed of our motion can change with time, we have to transform the simple quantity F*x, force times distance into an integral, F*dx, the dot product of force and dx. If the math isn't too clear to you, don't worry. The only thing you really need to remember is that work is equal to the force on an object times the distance over which it's applied.
Gravitational fields are nice, because they're what we call "conservative" fields. That means that it takes work to move up and down in a gravitational field, but not to go in any other direction. Of course, there are more rigerous mathematical definitions (e.g. curl(g) = 0), but basically, I have relayed to you the important information about conservative fields. Since it doesn't take any work to move left or right (or to circle around the earth, if you want to be technical), we can say that an object has a specific amount of potential energy at a certain height, no matter how it got there, and no matter where on earth it is.
This means that we could define a potential energy for the earth for every point in space, which would be a function of distance. Instead of being made up of vectors, like a force field, it would just be made up of scalers - that is to say, numbers, with no specific direction. However, it would still contain all of the information that the force field had in it, and we can calculate the force field from it simply by taking the gradient (if you don't know what a gradient is, don't worry. It doesn't really matter. Just know that it's the change in the potential energy with respect to distance expressed as a vector).
When an object moves up in a gravitational field, the force and the motion are pointing in opposite directions. However, we still want our potential energy to increase as we go up, instead of going down. The integral(F*dx) will be negative because F and dx have opposite signs. This means, in defining our potential "U", we need to flip the sign on our integral, so:
U = -Integral(F*dx)The fact that all of the information in the force field is contained within the potential should tell us that there's some way of doing physics using scaler potentials, rather than vector fields, and that is the topic that I'm going to cover in the rest of this tutorial.
There's one more quantity we need to define: Kinetic energy. Kinetic energy is basically the same as work. Work is simply the change in kinetic energy after a force has acted on an object. Kinetic energy, T, is calculated by:
T = Integral(F*dx)So how, then, is this different from the potential? Well, there are two differences.
1. The force F doesn't have to be solely from our gravitational field, like in the potential we calcluted. F in this case could also be from somebody pushing on the object, or a rocket firing, or even some other kind of field.
2: The sign is reversed. This means that as an object gets lower in a gravitational field, it's kinetic energy will go up (if no other forces are acting on it). This makes sense, because kinetic energy is related to velocity, and we all know that things speed up as they fall.
Because our kinetic energy might have some source other than the gravitational field, we need a way of defining it independant of whatever forces are acting on it. I hinted at this in #2 - the kinetic energy is related to the velocity. It's defined as:
T = 1/2m*v^2This is more or less all the background physics you need to know, however there are a few details that I'd like to clear up before moving on. It's mainly semantics, so if you're not all that interested in the physics, skip to the next section. However, to be completely rigerous, I need to point these things out.
When we defined work ealier, as the integral of F*dx, what I neglected to mention is the fact that we have to put limits on the integral. The integral takes place between two points, a, and b. So the work that we've defined is only the work that it takes to get from a to b.
When we define our potentials, we want to leave the limits off of our integral, to give us something more generic that can be used throughout all space. To be mathematically correct, though, that means that we have to add a constant + C to our integral, which could, in theory, be any number.
However, to do the physics, we can leave off the + C, because the really important thing isn't the actual value of the potential at any point in space, but rather, the way the potential changes throughout space. When looking at the change in the potential, the + C will drop out on its own, so it is never necessarry to write it in the first place.
Second of all, the quantity F is equal to some vector field multiplied by mass, in the case of gravity. It is often usefull to write a potential V as integral(F/m*dx), because it is more generic than what I'll call U, integral(F*dx). U is simply V*m, and thus V can be used for any object, regardless of mass.
Part II: The LagrangianThere's a very interesting behavior that objects obey, from which we can derive their equations of motion. Suppose you toss a ball up into the air at a certain speed, with a certain direction. We could figure out how it's going to move and where it's going to land using Newton's laws. But if we look it's motion, we notice there's a very special property about it's path that is different from every other path.
At any given point in time, an object on earth has a kinetic energy, which as described in the last section, depends on it's velocity, and a potential energy, which is usually just due to it's height above the ground (let's ignore any other force fields that might be present. Generally speaking, we only have to worry about gravity).
We can sum up the kinetic energy that our particle has, over all of the points in it's path, and do the same thing with the potential energy. Since all real paths have an infinite number of points in them, we need to make this sum into an integral.
To make things simple, let's say that we're throwing the ball straight up into the air, so we only have one coordinate to worry about - the y coordinate, height.
If we have our function y(t), which is y coordinate as a function of time, we can calcluate from it our potential and kinetic energies.
Our potential energy, is just some function of height, which we'll call U(y).
Our kinetic energy is a function of velocity. Velocity is a function of the time derivitive of y. The time derivitive of y(t), dy/dt, we'll call y'. Our kinetic energy, then, is some function T(y')
When we throw our ball up into the air, we start out with a high velocity, but very low to the ground. That means a high kinetic energy and low potential. As the ball gets higher and higher, the potential energy goes up, and the kinetic energy goes down. As it comes back down, the potential energy decreases again, and the kinetic energy goes up. We want to sum up the potential and kinetic energies at all the different times along the entire path.
The sum of our kinetic energy over the entire path is:
Integral(T(y'))The sum of our potential energy over the entire path is:
Integral(U(y))Now, let's take the difference of those two quantities, and call it L
L = Integral(T(y')) - Integral(U(y))Because of the properties of integrals, we can combine them into one:
L = Integral(T(y') - U(y))It turns out, that for the path our ball took, L is smaller (closer to zero - we should say the absolute value of L is smaller) than it would have been over any other path.
Of course, the initial kinetic energy of the ball depends on how hard we throw it. There's no way to get around that. But to make L smaller, the ball has to go up, so that T gets smaller and U gets bigger. However, as it goes up, it's kinetic energy will go down, until eventually U is larger than T, and |L| starts to get bigger again. There's no way around that. Eventually, the ball will completely stop, and U will be big and T will be small, so it will have to reverse direction, and fall back downward, so that U gets smaller and T gets larger again.
So how do we figure out what path does this? There's an interesting kind of calculus involved, which I'll describe below. If you're not interested in the math, skip this next section between the ---'s, and you can see the formula at the end.
----------------------
We want to find y(t), such that L(y, y') is minimized. Assume that we have the path y(t) that minimizes L. We know that y starts at point a and ends at point b.
If we add some other function to it, n(t), that doesn't change the start or end points, Integral(L(y+n, y'+n')dt) should be larger than Integral(L(y,y')dt).
If we multiply n(t) by alpha, we get Integral(L(y+alpha*n, y'+alpha*n')dt). We'll call this integral J.
J = Integral(L(y+alpha*n, y'+alpha*n')dt)J is maximized when alpha = 0. The problem is, we don't actually know what y+alpha*n and y'+alpha*n' are when alpha equals zero (because we don't know what y and y' are).
To find out, we take the derivitive of J with respect to alpha, and call it J':
J' = d/dalpha Integral(L(y+alpha*n, y'+alpha*n'))Following from regular calculus, J is maximized when J' = 0. So:
d/dalpha Integral(L(y+alpha*n, y'+alpha*n')) = 0since d/dalpha and the integral commute, we can rewrite this as:
Integral(d/dalpha L(y+alpha*n, y'+alpha*n')) = 0Let's define an new function Y, such that Y = y+alpha*n, so now we have:
Integral(d/dalpha L(Y,Y'))) = 0And:
Integral(d/dalpha L(Y, Y'))) = Integral(dL/dY*dY/dalpha + dL/dY'*dY'/dalpha) = 0since Y = y+alpha*n, dY/dalpha = n
and since Y' = y'+alpha*n', dY'/dalpha = n'
Integral(dL/dY*n + dL/dY'*n') = 0Since the second term, dL/dY'*n' = dL/dY'*dn/dt, we can integrate this by parts. Doing so, gives us [dL/dY'*n] - Integral(d/dt(dL/dY')*n). So our full integral becomes
Integral(dL/dY*n - d/dt(dL/dY')*n) + [dL/dY'*n] = 0I put dL/dY'*n in brackets because it must be evaluated from a to b. Since we know that n(t) goes to zero at a and b, this term goes to zero, leaving us with
Integral(dL/dY*n - d/dt(dL/dY')*n) = Integral((dL/dY - d/dt(dL/dY'))*n) = 0In order for the integral to go to zero, (dL/dY - d/dt(dL/dY'))*n must equal zero. Since n is an arbitrary function, we know it can't go to zero.
That means that:
dL/dY - d/dt(dL/dY') = 0Solving for Y, we get our function y(t), which minimizes L.
----------------------
So, now we have our equations of motion. If your problem has more than one dimension, just apply these equations to all of your dimensions. So, in the real world, where we have three dimensions, you would solve for:
dL/dX - d/dt(dL/dX') = 0
dL/dY - d/dt(dL/dY') = 0
dL/dZ - d/dt(dL/dZ') = 0and from that, you would get, X(t), Y(t), and Z(t). The x, y, and z coordinates of your object as a function of time. X', Y', and Z' denote the derivitives of these functions with respect to time (the x, y, and z components of velocity).
Part III: An ExampleLet's return to the problem of throwing a ball on earth. This time, let's not assume that it's getting thrown straight up, though. We'll do it in 3 dimensions, and solve the problem with the Legrangian.
We know that the force of gravity on earth falls off as 1/r^2. However, the earth is really large, and we're already really far away from the center, so our change in r, if we go up a few feet isn't that big compared to our distance from the center of the earth. This means, that to a good approximation, the force of gravity is constant with respect to height.
For most games, you'll want the force of gravity to be constant with respect to height. There's absolutely no reason for any land based game to have gravity fall off as 1/r^2, since if you did it right, you'd never be able to tell the difference.
I know I used feet two paragraphs ago, but I'm going to switch to meters, because it's the standard. The accelleration due to gravity at the surface of the earth is approximately constant equalling:
g = 9.8 m/s^2That's 9.8 meters per second per second (or about 32 ft/s^2). That means that when you're falling, every second you fall 9.8 meters per second faster than the last. Your accelleration, a is equal to g.
Since from Newton's laws, we know that
F = m*a and we know
a = -g, then the force of gravity is
F = -m*gthere is a negative sign infront of g because g pulls us downward.
Now, here's where you need to remember what we learned in the first section about potentials. We need to calculate the potential, U on earth, which is the integral of -F*dx. Since F is constant, though, we can just replace this with -F*X, force times distance.
If we lift an object off the ground to a height, y, we've moved it a distance y, and our potential becomes:
U = m*g*yAs always, our kinetic energy is:
T = 1/2*m*v^2So our Lagrangian, L is
L = 1/2*m*v^2 - m*g*yNow, we need to find out what v is in terms of x, y, and z.
Well, since velocity is the vector <x', y', z'> (where ' denotes the time derivitive, as before), the length of this vector, which we'll call v, is:
v = sqr(x'^2 + y'^2 + z'^2).Fortunately, what we're really interested in is v^2, so that nasty square root will disappear, and we get
v^2 = x'^2 + y'^2 + z'^2This is always true, for any problem, as long as you use rectangular (x,y,z) coordinates.
so, rewriting our L in terms of our formula for v^2, we get:
L = m*(1/2(x'^2 + y'^2 + z'^2) + g*y)plugging this into the formula we derived in the last section, we get:
dL/dx = 0
dL/dy = m*g
dL/dz = 0dL/dx' = m*x'
dL/dy' = m*y'
dL/dz' = m*z'and
d/dt(dL/dx') = m*x''
d/dt(dL/dy') = m*y''
d/dt(dL/dz') = m*z''
where '' denotes the second derivitive with respect to time (accelleration)
So, putting it all together:
0 - mx'' = 0
m*(g - y'') = 0
0 - mz'' = 0Which means that:
x'' = 0
y'' = g
z'' = 0This means that our ball isn't accellerating in the x or z directions, but it is accellerating in the z direction, at a rate of g. This makes sense, because the force of gravity is only acting in the y direction, and since there are no other forces, that should be the only direction of accelleration.
Solving the three equations we have, to find x, y, and z, we get:
x(t) = x_0 + v_x0*t
y(t) = y_0 + v_y0*t + 1/2*g*t^2
z(t) = z_0 + v_z0*t<x_0, y_0, z_0> is the location of the person who threw the ball, which we can specify to be anything we want. <v_x0, v_y0, v_z0> is the velocity that the ball was thrown at, which we can also specify to be anything we want.
This is the exact same answer as you would get using Newtons laws, but deriving it a different way. Admittedly, in this situation, it would have been just as easy, or easier to use Newtons laws, but there are many situations where it is not. I just used this is a simple example to show you how to go about solving problems this way.
Part IV: Applying it to a gameThe Lagrangian formalism seems all well and good, but the problem is, it involves derivitives and integrals, which we can't do with our computers, so it would seem that it's not very useful for computer programming. In reality, Newton's laws rely on derivitives and integrals as well, it's just that computer programmers use approximations in games to get around actually taking the derivitives and integrals.
What we need to remember is that we can find the path that minimizes the overall L by finding the direction to head at every point in time that minimizes L at that particular time. So we just need to get our object to follow the lagrange equations (approximately) at every cycle of our game loop.
The first thing we need to do is write some code that will hold our masless potential, V, as a function of x, y, and z. For a gravitational field, this is easy. It's just
Function VofX(x as single, y as single, z as single) as single
'declare g as a constant somewhere in the program
VofX = g*y
End Function
Our potential, U, that we use in the Lagrangian, is just
U = m*VofXwhere m is the mass of our particle (or vehicle - whatever object it is that you want to apply the physics to), defined somewhere else in the program.
For other fields, our potential wouldn't be so trivial. For example, if you wanted to write a function to calculate the potential of a planet in space, for some kind of space combat game, you would do something like
Function VofX(x as single, y as single, z as single) as single
Dim r as single
r = sqr(x*x + y*y + z*z)
'G_const is not the same as g. It's a small constant that determines how much force
'each unit of mass will put out. Also, M_planet should be defined somewhere.
'It is the mass of the planet.
VofX = -M_planet*G_const/r
End Function
But regardless of our potential, the process is the same. First, calculate a vector that is the change in the potential in the x, y, and z directions.
You can get this by doing:
'Vel is a vector that holds the velocity of our object
DeltaU.x = (VofX(x + Vel.x, y, z) - VofX(x - Vel.x, y, z))/(2*Vel.x)
DeltaU.y = (VofX(x, y + Vel.y, z) - VofX(x, y - Vel.y, z))/(2*Vel.y)
DeltaU.z = (VofX(x, y + .1, z + Vel.z) - VofX(x, y, z - Vel.z))/(2*Vel.z)
In cartesian coordinates, since our potential, U, isn't dependant on velocity (at least for a gravitational field. Things get more complicated with magnetic fields), d/dt(dL/dx'), d/dt(dL/dy'), and d/dt(dL/dz') are always the same. They are:
m*x'',
m*y'', and ,
m*z'', respectively.
We can use this fact to calculate our accellerations, which we can then use to change our velocities.
Pluggin in our calculations into the Lagrange equations, we get
Function Update Position()
'Accel is a vector holding our accelleration. m is our mass, as usual.
Accel.x = 1/m * DeltaU.x
Accel.y = 1/m * DeltaU.y
Accel.z = 1/m * DeltaU.z
'Now, add the accelleration to the velocity. We could have just added 1/m * DeltaU,
'but I chose to store our accelleration first, to illustrate the point about how it is
'calculated.
Vel.x = Vel.x + Accel.x
Vel.y = Vel.y + Accel.y
Vel.z = Vel.z + Accel.z
'Now, add our velocity to our position, to get our new position
Pos.x = Pos.x + Vel.x
Pos.y = Pos.y + Vel.y
Pos.z = Pos.z + Vel.z
End function
And there you have it - an implementation of the Lagrangian formalism into your program. All you need to do is set the function VofX to whatever particular potential you're using in your game.
So far, however, we haven't seen how implementing this formalism would be more beneficial than using Newton's. In fact, since all we're doing in the above example is recalculating our forces from the potential, and getting accellerations from them, if we just continue using the Lagrangian like this, it will be exactly the same as an implementation of Newton's laws, only slower.
In the next section, I will show you where the true power of the Lagrangian lies, and how it can provide much easier answers to certain problems than Newton's laws.
Part V: Advanced topics - generalized coordinatesAs I said before, in the preceeding example, our implementation of the Lagrangian is actually less efficient and more difficult to figure out than an implementation of Newtonian physics, since it involves calculating a potential, then, in essence, recalculating forces from it.
However, there are certain situations where it is very difficult to use Newton's laws, but the Lagrangian formalism may give us insight into how to solve the problem.
Take for example, the problem of a swinging pendulum. We'll make the same approximations as we did before, namely that the gravitational force is constant with respect to height. The pendulum, however, doesn't simply move up and down, it swings from side to side, and is constrained to move along a circular path.
The force on the pendulum isn't just the force of gravity, it's the force of the rod, pulling or pushing on the weight at the end, forcing it to keep it's (semi)circular path. To get the forces to use in Newton's laws, we have to project gravity onto a vector parallel to the velocity of the pendulum, and go through several difficult step to get things to come out right.
Such a situation is a situation of constrained motion. In this case, our weight at the end of a pendulum is constrained to a circular path. In situations like this, the Lagrangian can provide very easy solutions to our problems.
There are two ways to get a solution to this problem with the Lagrangian. One is to do exactly what we did before, except throw in something called "Lagrange multipliers". This method is nice because it will also spit out the forces that could be used with Newton's laws. However, it is not the simplest, or most elegant solution, so I won't cover it here.
The other way to solve this problem is to use something called generalized coordinates.
What are generalized coordinates? They're exactly what the name says. Who says that our coordinate system has to be cartesian? Why do we have to use x, y, and z coordinates? Why not something else?
The answer is, we can. There's no reason to use x, y, and z as our coordinates, if there's something more efficient for our purposes. And the best part is, the Lagrangian will still work!
Why use a different set of coordinates? Well, let's think. What do we know about this situation with the pendulum?
First of all, the z coordinate can't change, because the pendulum only swings back and forth along the x axis, moving up and down. So let's throw out z (Even if we want the pendulum to be at an agle with respect to the x axis, it's only moving in one horizontal dimension, so we can simply rotate the vector of motion at the end).
Now that that's out of the way, let's think about what else we know. Since the pendulum has to move on a circle, a natural choice of coordinates would be polar coordinates. We can describe the location of our pendulum in terms of r, the radius and theta, the angle it makes with the vertical axis.
But we also know that the radius of our pendulum can't change, so we can throw out r. Now all we're left with is theta, the angle our pendulum makes with the vertical axis. We've just narrowed the number of coordinates we have from three down to one!
What we need to do now is calculate T and U in terms of our new coordinate.
In our coordinate system
X = R*sin(theta)
Y = -R*cos(theta)Remember, R is a constant, not a coordinate.
When the angle theta with the vertical is zero, our pendulum is at the bottom, and when the angle is pi/2, our pendulum is facing straight off to the side.
You might have noticed that Y becomes negative when theta is zero. We could write Y as
Y = -R*cos(theta) + cwhere c is the height of the pendulum off the ground. But there's really no point, since the constant c will just drop out of our equations anyway, since our potential U is linear with height.
To calculate kinetic energy, we need X'^2 + Y'^2. Differentiating X and Y with respect to time, we get:
X' = R*Cos(theta)*theta' and
Y' = R*Sin(theta)*theta'so:
X'^2 + Y'^2 = v^2 = R^2*(Cos(theta)^2 + Sin(theta)^2)*theta'^2And by trig identities:
v^2 = R^2*theta'^2So T and U, and L are:
T = 1/2*m*R^2*theta'^2
U = -m*g*R*Cos(theta)
L = T - U = m*(1/2*R^2*theta'^2 + Cos(theta)Plugging this into our Lagrange equations, we get:
-m*Sin(theta) - m*R^2*theta'' = 0 or
Sin(theta) + R^2*theta'' = 0Providing that I haven't made any mistakes

The equation
Sin(theta) + R^2*theta'' = 0 is impossible to solve exactly by hand. However, we can calculate it approximately, which means that our physics game engine could hand it just fine.
Here's a function that will update the location of the end of our pendulum as a function of time:
Function UpdatePend()
'R is a constant defined somewhere else in the program.
'Theta is a single, and ThetaAccel is a single that holds the change in ThetaVel.
'ThetaVel is a singel that holds the change in Theta with each cycle.
'Pos is a vector that holds position
ThetaAccel = Sin(theta)/R^2
ThetaVel = ThetaVel + ThetaAccel
Theta = Theta + ThetaVel
Pos.x = R*Sin(theta)
Pos.Y = -R*Cos(theta)
End Function
As you can see, we have come up with a relatively simple set of equations, and a very simple function to describe the motion of a pendulum from our somewhat ugly and daunting Lagrangian. You can apply this method of using generalized coordinates to just about any situation.
ConclusionAlthough it was originally my intention to provide an introduction to the Hamiltonian as well, I feel like I've gone on long enough and will leave that for another day. Hopefully the introduction I've given to the Lagrangian will be of some use to some programmers out there.
Remember that the true usefulness of the Lagrangian doesn't come from the way it describes the equations of motion, but rather, from the way that it allows you to find the equations of motion. It is a usefull tool in game physics for finding out how an object is supposed to act when it would be difficult to program in all the different forces that are acting on it. For situations of constrained motion, the Lagrangian is a very useful tool.
I can see that it might be useful to apply the Lagrangian to a game that uses a landscape. By constraining your land vehicle to move along the ground, the Lagrangian could describe the motion of the vehicle, even if it would be difficult to find the exact force that the ground exherts on the vehicle. I won't try to figure out a good method to put in this tutorial, but rather, will leave it to you as an interesting problem to solve, if you would like.