Producing a forward/directional vector from just the euler rotation components and position - math

I'm currently have quite a lot of trouble producing a forward vector based on my accessible transform components. I'm working within SparkAR, where objects are built around a transform class with position, rotation (euler) and scale, as expected, however it doesn't provide any built in methods for retreiving general information such as the relative forward and up vector of the object, a transform matrix, etc.
This leaves me with the task of trying to put this together myself from the available data. The end result is simply to be able to calculate the angle between the forward vector of 2 objects, which is mapped to a 0-1 range and used as a value of texture blending. The goal is for it to simulate fake dynamic lighting through texture blends based on how similar the local object's forward vector is to the forward vector of the directional light.
I must have read 20+ different StackOverflow results by this point covering similar questions, however I've been unable to get correct results based on my testing using their suggestions, and at this point I feel like I need some more direct feedback to my method before I tear my eyes out.
My current process is as follows:
1) Retrieve euler rotation from the animated joint I want to compare against (it's in radians)
2) Convert radian values to degrees
3) Attempt to convert the euler values to a forward vector using the following calculation sample:
x = cos(yaw)cos(pitch)
y = sin(yaw)cos(pitch)
z = sin(pitch)
I tried a couple of other variations on that for different axis orders, which didn't provide much of a change at all.
Some small notes before continuing, X is pitch, Y is yaw and Z is roll. Positive Z is towards the screen, positive X is to the right, positive Y is up.
4) Normalise the vector (although it's unnecessary given the results I get).
5) Perform a dot product operation on the vector, against a set direction vector, in this case for testing purposes, I'm simply using (0,0,1).
6) Compare the resulting value against the expected result - incorrect.
Within a single 90 degree return, the value retreived from the dot product, which by my understanding should be 1 when facing the same direction, and -1 when facing inverse, oscillates between these two range endpoints between 15-20 times.
Another thing worth noting here, is that I did have to swap the Y and Z components of the calculation to produce a non-0 result, so the current forward vector calculation from euler is as follows:
x = cos(yaw)cos(pitch)
y = sin(pitch)
z = sin(yaw)cos(pitch)
I'm really not sure where to go about moving on from here to produce the result I'm looking for, as I simply don't understand what about the current calculations are going wrong to begin fixing it.
The passed in vector, pre-dot product at the rotations 0, 90, 180 and 270 are as follows:
( 1 , 0, -0.00002)
(-0.44812, 0, -0.89397)
( 1 , 0, 0.00002)
(-0.44812, 0, 0.89397)
I can see that the euler angles going into the calculations are definitely correct, so the RadToDeg conversion isn't screwing the input up.
Is the calculation I'm using for trying to produce a forward vector from euler rotations incorrect? Is there something I should be using instead?
Any advice on moving forward with this issue would be much appreciated.
Thanks.

Related

Generate random point on a 2D disk in 3D space given normal vector

Is there a simple and efficient method to generate a random (uniformly distributed) point on a disk "hanging" in 3-dimensional space? The disk is defined by its normal.
Ideally, I would like to avoid rotation matrices, as I do not fully understand them, and I know they have issues.
So far, I've tried generating a 3D unit vector and projecting it onto the plane of the disk, which does ensure that the point is within the disk, but not that it's uniformly distributed.
I also tried scaling the generated vector according to some function of its length, but I couldn't get a uniform distribution back regardless.
I had an idea that involved creating 2 vectors perpendicular to each other and the normal, to define a local coordinate system. Then I could generate a point on the unit disk as in 2D and convert the result back to the global coordinate system. This seems like it would be quite efficient, as it involves some precomputation (which I'm completely fine with) and only simple calculations afterwards (this is for a raytracer, so it'll happen a lot). The problem is, I don't know how to reliably calculate the local coordinate system's basis vectors while avoiding possible issues like collinearity.
Any help is much appreciated.
A easy way to calculate orthogonal basis vectors u, v for a plane with normal n = (a,b,c) is finding the component with least absolute value, and making u orthogonal to that component; the rest pretty much follows. For example, if the first component is the one with minimal absolute value, you can pick these basis vectors:
u = (0, -c, b) // n·u = -bc+cb = 0
v = (b²+c², -ab, -ac) // n·v = ab²+ac²-ab²-ac² = 0, u·v = abc-abc = 0

What is the need for normalizing a vector?

Trying to understand vectors a bit more.
What is the need for normalizing a vector?
If I have a vector, N = (x, y, z)
What do you actually get when you normalize it - I get the idea you have to divide x/|N| y/|N| & z/|N|. My question is, why do we do this thing, I mean what do we get out of this equation?
What is the meaning or 'inside' purpose of doing this.
A bit of a maths question, I apologize, but I am really not clear in this topic.
For any vector V = (x, y, z), |V| = sqrt(x*x + y*y + z*z) gives the length of the vector.
When we normalize a vector, we actually calculate V/|V| = (x/|V|, y/|V|, z/|V|).
It is easy to see that a normalized vector has length 1. This is because:
| V/|V| | = sqrt((x/|V|)*(x/|V|) + (y/|V|)*(y/|V|) + (z/|V|)*(z/|V|))
= sqrt(x*x + y*y + z*z) / |V|
= |V| / |V|
= 1
Hence, we can call normalized vectors as unit vectors (i.e. vectors with unit length).
Any vector, when normalized, only changes its magnitude, not its direction. Also, every vector pointing in the same direction, gets normalized to the same vector (since magnitude and direction uniquely define a vector). Hence, unit vectors are extremely useful for providing directions.
Note however, that all the above discussion was for 3 dimensional Cartesian coordinates (x, y, z). But what do we really mean by Cartesian coordinates?
Turns out, to define a vector in 3D space, we need some reference directions. These reference directions are canonically called i, j, k (or i, j, k with little caps on them - referred to as "i cap", "j cap" and "k cap"). Any vector we think of as V = (x, y, z) can actually then be written as V = xi + yj + zk. (Note: I will no longer call them by caps, I'll just call them i, j, k). i, j, and k are unit vectors in the X, Y and Z directions and they form a set of mutually orthogonal unit vectors. They are the basis of all Cartesian coordinate geometry.
There are other forms of coordinates (such as Cylindrical and Spherical coordinates), and while their coordinates are not as direct to understand as (x, y, z), they too are composed of a set of 3 mutually orthogonal unit vectors which form the basis into which 3 coordinates are multiplied to produce a vector.
So, the above discussion clearly says that we need unit vectors to define other vectors, but why should you care?
Because sometimes, only the magnitude matters. That's when you use a "regular" number (something like 4 or 1/3 or 3.141592653 - nope, for all you OCD freaks, I am NOT going to put Pi there - that shall stay a terminating decimal, just because I am evil incarnate). You would not want to thrown in a pesky direction, would you? I mean, does it really make sense to say that I want 4 kilograms of watermelons facing West? Unless you are some crazy fanatic, of course.
Other times, only the direction matters. You just don't care for the magnitude, or the magnitude just is too large to fathom (something like infinity, only that no one really knows what infinity really is - All Hail The Great Infinite, for He has Infinite Infinities... Sorry, got a bit carried away there). In such cases, we use normalization of vectors. For example, it doesn't mean anything to say that we have a line facing 4 km North. It makes more sense to say we have a line facing North. So what do you do then? You get rid of the 4 km. You destroy the magnitude. All you have remaining is the North (and Winter is Coming). Do this often enough, and you will have to give a name and notation to what you are doing. You can't just call it "ignoring the magnitude". That is too crass. You're a mathematician, and so you call it "normalization", and you give it the notation of the "cap" (probably because you wanted to go to a party instead of being stuck with vectors).
BTW, since I mentioned Cartesian coordinates, here's the obligatory XKCD:
Reading Godot Game Engine documentation about unit vector, normalization, and dot product really makes a lot of sense. Here is the article:
Unit vectors
Ok, so we know what a vector is. It has a direction and a magnitude. We also know how to use them in Godot. The next step is learning about unit vectors. Any vector with magnitude of length 1 is considered a unit vector. In 2D, imagine drawing a circle of radius one. That circle contains all unit vectors in existence for 2 dimensions:
So, what is so special about unit vectors? Unit vectors are amazing. In other words, unit vectors have several, very useful properties.
Can’t wait to know more about the fantastic properties of unit vectors, but one step at a time. So, how is a unit vector created from a regular vector?
Normalization
Taking any vector and reducing its magnitude to 1.0 while keeping its direction is called normalization. Normalization is performed by dividing the x and y (and z in 3D) components of a vector by its magnitude:
var a = Vector2(2,4)
var m = sqrt(a.x*a.x + a.y*a.y)
a.x /= m
a.y /= m
As you might have guessed, if the vector has magnitude 0 (meaning, it’s not a vector but the origin also called null vector), a division by zero occurs and the universe goes through a second big bang, except in reverse polarity and then back. As a result, humanity is safe but Godot will print an error. Remember! Vector(0,0) can’t be normalized!.
Of course, Vector2 and Vector3 already provide a method to do this:
a = a.normalized()
Dot product
OK, the dot product is the most important part of vector math. Without the dot product, Quake would have never been made. This is the most important section of the tutorial, so make sure to grasp it properly. Most people trying to understand vector math give up here because, despite how simple it is, they can’t make head or tails from it. Why? Here’s why, it’s because...
The dot product takes two vectors and returns a scalar:
var s = a.x*b.x + a.y*b.y
Yes, pretty much that. Multiply x from vector a by x from vector b. Do the same with y and add it together. In 3D it’s pretty much the same:
var s = a.x*b.x + a.y*b.y + a.z*b.z
I know, it’s totally meaningless! You can even do it with a built-in function:
var s = a.dot(b)
The order of two vectors does not matter, a.dot(b) returns the same value as b.dot(a).
This is where despair begins and books and tutorials show you this formula:
A ⋅ B = ∥A∥ ∥B∥ cos(θ)
And you realize it’s time to give up making 3D games or complex 2D games. How can something so simple be so complex? Someone else will have to make the next Zelda or Call of Duty. Top down RPGs don’t look so bad after all. Yeah I hear someone did pretty will with one of those on Steam...
So this is your moment, this is your time to shine. DO NOT GIVE UP! At this point, this tutorial will take a sharp turn and focus on what makes the dot product useful. This is, why it is useful. We will focus one by one in the use cases for the dot product, with real-life applications. No more formulas that don’t make any sense. Formulas will make sense once you learn what they are useful for.
Siding
The first useful and most important property of the dot product is to check what side stuff is looking at. Let’s imagine we have any two vectors, a and b. Any direction or magnitude (neither origin). Does not matter what they are, but let’s imagine we compute the dot product between them.
var s = a.dot(b)
The operation will return a single floating point number (but since we are in vector world, we call them scalar, will keep using that term from now on). This number will tell us the following:
If the number is greater than zero, both are looking towards the same direction (the angle between them is < 90° degrees).
If the number is less than zero, both are looking towards opposite direction (the angle between them is > 90° degrees).
If the number is zero, vectors are shaped in L (the angle between them is 90° degrees).
So let’s think of a real use-case scenario. Imagine Snake is going through a forest, and then there is an enemy nearby. How can we quickly tell if the enemy has seen discovered Snake? In order to discover him, the enemy must be able to see Snake. Let’s say, then that:
Snake is in position A.
The enemy is in position B.
The enemy is facing towards direction vector F.
So, let’s create a new vector BA that goes from the guard (B) to Snake (A), by subtracting the two:
var BA = A - B
Ideally, if the guard was looking straight towards snake, to make eye to eye contact, it would do it in the same direction as vector BA.
If the dot product between F and BA is greater than 0, then Snake will be discovered. This happens because we will be able to tell that the guard is facing towards him:
if (BA.dot(F) > 0):
print("!")
Seems Snake is safe so far.
Siding with unit vectors
Ok, so now we know that dot product between two vectors will let us know if they are looking towards the same side, opposite sides or are just perpendicular to each other.
This works the same with all vectors, no matter the magnitude so unit vectors are not the exception. However, using the same property with unit vectors yields an even more interesting result, as an extra property is added:
If both vectors are facing towards the exact same direction (parallel to each other, angle between them is 0°), the resulting scalar is 1.
If both vectors are facing towards the exact opposite direction (parallel to each other, but angle between them is 180°), the resulting scalar is -1.
This means that dot product between unit vectors is always between the range of 1 and -1. So Again...
If their angle is 0° dot product is 1.
If their angle is 90°, then dot product is 0.
If their angle is 180°, then dot product is -1.
Uh.. this is oddly familiar... seen this before... where?
Let’s take two unit vectors. The first one is pointing up, the second too but we will rotate it all the way from up (0°) to down (180° degrees)...
While plotting the resulting scalar!
Aha! It all makes sense now, this is a Cosine function!
We can say that, then, as a rule...
The dot product between two unit vectors is the cosine of the angle between those two vectors. So, to obtain the angle between two vectors, we must do:
var angle_in_radians = acos( a.dot(b) )
What is this useful for? Well obtaining the angle directly is probably not as useful, but just being able to tell the angle is useful for reference. One example is in the Kinematic Character demo, when the character moves in a certain direction then we hit an object. How to tell if what we hit is the floor?
By comparing the normal of the collision point with a previously computed angle.
The beauty of this is that the same code works exactly the same and without modification in 3D. Vector math is, in a great deal, dimension-amount-independent, so adding or removing an axis only adds very little complexity.
That's a bit like asking why we multiply numbers. It comes up all the time.
The Cartesian coordinate system that we use is an orthonormal basis (consists of vectors of length 1 that are orthogonal to each other, basis means that any vector can be represented by a unique combination of these vectors), when you want to rotate your basis (which occurs in video game mechanics when you look around) you use matrices whose rows and columns are orthonormal vectors.
As soon as you start playing around with matrices in linear algebra enough you will want orthonormal vectors. There are too many examples to just name them.
At the end of the day we don't need normalized vectors (in the same way as we don't need hamburgers, we could live without them, but who is going to?), but the similar pattern of v / |v| comes up so often that people decided to give it a name and a special notation (a ^ over a vector means it's a normalized vector) as a shortcut.
Normalized vectors (also known as unit vectors) are, basically, a fact of life.
You are making its length 1 - finding the unit vector that points in the same direction.
This is useful for various purposes, for example, if you take the dot product of a vector with a unit vector you have the length of the component of that vector in the direction of the unit vector.
The normals are supposed to be used as a direction vector only. They are used for lighting computation, which requires normalized normal vectors.
This post is very old, but there still isn't a very clear answer as to why we normalize. The reason is to find the exact magnitude of the vector and it's projection over another vector.
Example: Projection of vector a over b is b·cos(θ)
However, in the case of dot products, the dot product of two vectors a and b is a·b·cos(θ). This means the dot product is the projection of a over b times a. So we divide it by a to normalize to find the exact length of the projection which is b·cos(θ).
Hope it's clear.

Trying to find the relative transformation between to two positions - XNA

I have written a simple AR program in XNA and I am now trying to find the relative transformation between my 2 markers.
I have located my markers relative to my camera and have extracted out translation and rotation matrixes for the markers.
What I am trying to do is to find out the relative translation to get to marker 2 from marker 1. For instance if marker 1 and marker 2 were lying on the same Z plane the Z translation component would be 0mm.
The image below is the application working for 2 positions on the same plane:
I assumed that by simply multiplying the matrix of the 2nd marker by the inverse of the 1st marker I can get the translation. However I am getting completely wrong results.
The code I am running is as follows:
posit.EstimatePose(points, out matrix, out trans);
float yaw, pitch, roll;
matrix.ExtractYawPitchRoll(out yaw, out pitch, out roll);
Matrix rotation =
Matrix.CreateFromYawPitchRoll(-yaw, -pitch, roll);
Matrix translation =
Matrix.CreateTranslation(new Vector3(trans.X, trans.Y, -trans.Z));
Matrix complete = rotation * translation;
List<Matrix> all = new List<Matrix>();
all.Add(rotation);
all.Add(translation);
all.Add(complete);
matrixes.Add(all);
}
Matrix res = Matrix.Invert(matrixes[0][2]) * matrixes[1][2];
Vector3 scaleR;
Vector3 translationR;
Quaternion rotationR;
res.Decompose(out scaleR, out rotationR, out translationR);
The result:
TranslationR : {X:-103.4285 Y:-104.1754 Z:104.9243}
I have overlaid 3D axes onto the image as shown above using XNA so I assume the rotation and translation relative to the camera has been worked out correctly.
It seems like I am doing something wrong along the way to calculate the translation. I would definitely not expect the Z to equal 104mm. I was expecting something along the lines of:
{X:0 Y:150 Z:0}
I've done something similar to this before, however it was using 3x3 matrices in a 2D environment (with X,Y Translate, Rotate, Skew). Are the matrices in question 4x4?
Yes you are right, to find the matrix to transform object A with matrix M1 to object B with matrix M2 you can compute M1' * M2 (where M1' is the inverse).
The problem you may be running into is that a Matrix is composed of rotation, translation, scale and other transformations (e.g. skew/perspective). Decomposing the matrix into its component parts often yields a non-deterministic answer. Its like Quadratic equations, there is more than one solution.
Another issue may be that Matrix operations are not commutative and you are simply performing them the wrong way around. If you perform M1' * M2 and M2 * M1' you will get different results.
Please give it a try (switching the matrix order). Also I'd be looking up the matrix decomposition function you used - what value of Rotation & Scaling are you getting at the output? Are your objects rotated or scaled? If not then you should get zero. Note that it is possible to have more than one solution of rotation + translation to get the same end result and the decomposition function doesn't know which it is you are looking for.
To extract just the translation component, you can use the methods form this page:
vt = (M14, M24, M34)T
What do you get when you try that?
What I am trying to do is to find out the relative translation to get
to marker 2 from marker 1.
Vector3 relativeTranslation = Marker2Matrix.Translation - marker1Matrix.Translation;
My answer seems overly simplistic so maybe I'm not grasping your question completely, but it will create a vector that when added to Marker1's location (translation), will get you to Marker 2's location.

Trajectory -math, c#

I am trying to map a trajectory path between two point. All I know is the two points in question and the distance between them. What I would like to be able to calculate is the velocity and angle necessary to hit the end point.
I would also like to be able to factor in some gravity and wind so that the path/trajectory is a little less 'perfect.' Its for a computer game.
Thanks F.
This entire physical situation can be described using the SUVAT equations of motion, since the acceleration at all times is constant.
The following explanation presumes understanding of basic algebra and vector maths. If you're not familiar with it, I strongly recommend you go read up on it before attempting to write the sort of game you have proposed. It also assumes you're dealing with 2D, though if you're dealing with 3D most of the same applies, since it's all in vector form - you just end up solving a cubic instead of quadratic, for which it may be best to use a numerical solver.
Physics
(Note: vectors represented in bold.)
Basically, you'll want to start by formulating your equation for displacement (in vector form):
r = ut + (at^2)/2
r is the displacement relative to the start position, u is the initial velocity, a is the acceleration (constant at all times). t is of course time.
a is dependent on the forces present in your system. In the general case of gravity and wind:
a = F_w/m - g j
where i is the unit vector in the x direction and j the unit vector in the y direction. g is the acceleration due to gravity (9.81 ms^-2 on Earth). F_w is the force vector due to the wind (this term disappears for no wind) - we're assuming this is constant for the sake of simplicity. m is the mass of the projectile.
Then you can simply substitute the equation for a into the equation for r, and you're left with an equation of three variables (r, u, t). Next, expand your single vector equation for r into two scalar equations (for x and y displacement), and use substitution to eliminate t (maths might get a bit tricky here). You should be left with a single quadratic equation with only r and u as free variables.
Now, you want to solve the equation for r = [target position] - [start position]. If you pick a certain magnitude for the initial velocity u (i.e. speed), then you can write the x and y components of u as U cos(a) and U sin(a) respectively, where U is the initial speed, and a the initial angle. This can be rearranged and with a bit of trignometry, you can finally solve for the angle a, giving you the launch velocity!
Algorithm
Most of the above description should be worked out on paper first. Then, it's simply a matter of writing a function to solve the quadratic formula and apply some inverse trigonometric functions to get the result.
P.S. Sorry for all the maths/physics in this post, but it was unavoidable! The OP seemed to be asking more about the physical rather than computational side of this, anyway, so that's what I've provided. Hopefully this is still useful to both the OP and other people.
The book:
Modern Exterior Ballistics: The Launch and Flight Dynamics of Symmetric Projectiles ISBN-13: 978-0764307201
Is the modern authority on ballistics. For accuracy you'll need the corrections:
http://www.dexadine.com/mccoy.html
If you need something free and less authoritative, Dr. Mann's 1909 classic The bullet's flight from powder to target is available on books.google.com.
-kmarsh
PS Poor ballistics in games is a particular pet peeve of mine, especially the "shoots flat to infinity" ballistic model.
As people have mentioned, while figuring out the angles between the points is relatively easy, determining the way that wind and gravity will affect the shot is more difficult.
Wind and gravity are both accelrating forces, though they act somewhat differently.
Gravity is easier, since it has both a constant direction (down) and magnitude regardless of the object. (Assuming that you're not shooting things with ridiculously high velocities). To calculate how gravity will affect the velocity of your object, just take the time since you last updated the velocity of the object, multiply it by your gravitational factor, and add it to your current velocity vector.
As a simple example, let's think of an object that is moving with a velocity of (3, 4, 7) in the x, y, z directions, with z being parallel with the force of gravity. You decide that your gravity value is -.3 You are ready to calculate the new velocity. When you check, you discover that 10 time units have passed since your last calculation (whatever your time units are...perhaps ticks or something). You take your time units (10), multiply by your gravity (-.3), which gives you -3. You add that to your Z, and your new velocity is (3, 4, 4). That's it. (This has been very simplified, but that should get you started.)
Wind is a bit different, if you want to do it right. If you want to do it a simple and easy way, you can make it like gravity...a constant force in a particular direction. But a more realistic way is to have the force be dependent on your current velocity vector. Put simply: if you're moving exactly with the wind, it shouldn't impart any force onto you. In this case, you simply calculate the magnitude of the force as the difference between its direction and your own.
A simple example of this might be if you were moving at (3, 0, 0), and the wind was moving at (5, 0, 0), and we can give the wind a strength of .5. (You also have to multiply by the time elapsed...for the sake of this example, to keep it simple, we'll leave the time-elapsed factor at 1) You calculate the difference in the vectors and multiply by your time difference (1), and discover that the difference is (2, 0, 0). You then multiply that vector by the wind strength, .5, and you discover that your velocity change is (1, 0, 0). Add that to your previous velocity, and you get (4, 0, 0)...so the wind has sped the object up slightly. If you waited another single time unit, you would have a difference of (1, 0, 0), multiplied by your strength of .5, so your final velocity would then be (4.5, 0, 0). As you can see, the wind provides less force as you become closer to it in velocity.) This is kind of neat, but may be overly complex for game ballistics.
The angle is easy, atan2(pB.x-pA.x,pB.y-pA.y). The velocity vector should be (pB-pA)*speed. And to add gravity/wind (gravity is just wind with a negative y component) add the (scaled) wind vector to your velocity at every simulation tick (you're basically adding it as acceleration).
Just a link, sorry : http://www.gamedev.net/reference/articles/article694.asp.
There is a lot of papers about game physics at gamedev. Have a look.
(BTW : wind only add some velocity to an object. The hard part is gravity.)

Calculating rotation along a path

I am trying to animate an object, let's say its a car. I want it go from point
x1,y1,z1
to point x2,y2,z2 . It moves to those points, but it appears to be drifting rather than pointing in the direction of motion. So my question is: how can I solve this issue in my updateframe() event? Could you point me in the direction of some good resources?
Thanks.
First off how do you represent the road?
I recently done exactly this thing and I used Catmull-Rom splines for the road. To orient an object and make it follow the spline path you need to interpolate the current x,y,z position from a t that walks along the spline, then orient it along the Frenet Coordinates System or Frenet Frame for that particular position.
Basically for each point you need 3 vectors: the Tangent, the Normal, and the Binormal. The Tangent will be the actual direction you will like your object (car) to point at.
I choose Catmull-Rom because they are easy to deduct the tangents at any point - just make the (vector) difference between 2 other near points to the current one. (Say you are at t, pick t-epsilon and t+epsilon - with epsilon being a small enough constant).
For the other 2 vectors, you can use this iterative method - that is you start with a known set of vectors on one end, and you work a new set based on the previous one each updateframe() ).
You need to work out the initial orientation of the car, and the final orientation of the car at its destination, then interpolate between them to determine the orientation in between for the current timestep.
This article describes the mathematics behind doing the interpolation, as well as some other things to do with rotating objects that may be of use to you. gamasutra.com in general is an excellent resource for this sort of thing.
I think interpolating is giving the drift you are seeing.
You need to model the way steering works .. your update function should 1) move the car always in the direction of where it is pointing and 2) turn the car toward the current target .. one should not affect the other so that the turning will happen and complete more rapidly than the arriving.
In general terms, the direction the car is pointing is along its velocity vector, which is the first derivative of its position vector.
For example, if the car is going in a circle (of radius r) around the origin every n seconds then the x component of the car's position is given by:
x = r.sin(2πt/n)
and the x component of its velocity vector will be:
vx = dx/dt = r.(2π/n)cos(2πt/n)
Do this for all of the x, y and z components, normalize the resulting vector and you have your direction.
Always pointing the car toward the destination point is simple and cheap, but it won't work if the car is following a curved path. In which case you need to point the car along the tangent line at its current location (see other answers, above).
going from one position to another gives an object a velocity, a velocity is a vector, and normalising that vector will give you the direction vector of the motion that you can plug into a "look at" matrix, do the cross of the up with this vector to get the side and hey presto you have a full matrix for the direction control of the object in motion.

Resources