Solving y on a triangle in 3D space given x and z.

November 25, 2009 at 11:53 am (C++) (, , , , )

Yay, my second post.

I’ve been working on a final project at my university, University of Reykjavik for a computer graphics class.
Since I’ve always wanted to create a terrain engine since I was a kiddie, I thought why not? This was my opportunity to do it for once!

The problem I was facing was walking on the surface of the terrain. The y position of the camera was the max of the three points of the triangle I was standing on, which made the movement jerky, like stepping um stairs.

So how can we find the height or the y value for a specific x and z in a triangle? Easy, really! We’ll have to find the equation of a plane from 3 points. But first we need to define two vectors that lie on the plane:

Vector3 is a class of which has three floats; x, y and z.

Vector3 AB(points[1].x – points[0].x, points[1].y – points[0].y, points[1].z – points[0].z);
Vector3 AC(points[2].x – points[0].x, points[2].y – points[0].y, points[2].z – points[0].z);

So now we have two vectors AB and AC, which define a plane from the three points points[0], points[1] and points[2].

Next we’ll have to find the cross product of those two vectors: AB x AC, which will give us the normal vector of the plane.

Vector3 normal(AB.y * AC.z – AB.z * AC.y, AB.z * AC.x – AB.x * AC.z, AB.x * AC.y – AB.y * AC.x);

Normal vector

So now we have the normal vector of the plane. Normal vector is a vector which is perpendicular to the plane.

Next we’ll need to multiply one point of the three points that define the plane with the normal vector to get the equation of the plane.

Basically it’ll give us a number that I call the coefficient:

coefficient =normal.x * points[0].x +normal.y * points[0].y +normal.z * points[0].z;

So now we can get the height for a given x and z in the triangle!

height = (-normal.x*position.x -normal.z * position.z + coefficient) /normal.y;

Reference:
http://www.jtaylor1142001.net/calcjat/Solutions/VPlanes/VP3Pts.htm

Advertisements

1 Comment

  1. My latest work (TerrainGL). « I feel, therefore I am. said,

    […] The collision detection was really simple to do, for each surface made up of 2 triangles, I found the equation of the two triangles and solved y from x and z. I wrote a tutorial on that HERE. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: