Jump to content
  • Advertisement
Sign in to follow this  
Scet

2D line-segment - line intersection?

This topic is 4532 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is probably a simple problem, but my math skills aren't that sharp. What I have is a line segment from (x1,z1) to (x2,z2) and a value z. z represents a horizontal, one-dimensional line. I've gotten to the point where I can tell if z is between the segment's points. Now I'm stuck though, I have no idea how to get the intersection point. Point consists of two variables: X and Z
		public static Point LinePlaneIntersection( Point A, Point B, short Z )
		{
			if( A.Z == Z )
			{
				return A;
			}
			if( B.Z == Z )
			{
				return B;
			}
			if( A.Z < B.Z )
			{
				if( ( Z < A.Z ) || ( Z > B.Z ) )
				{
					return null;
				}
			}
			else
			{
				if( ( Z < B.Z ) || ( Z > A.Z ) )
				{
					return null;
				}
			}
			// intersection test should go here
			return null;
		}

Anyone have any ideas? I thought about getting the slope, but what do I do after that?

Share this post


Link to post
Share on other sites
Advertisement
Try:
float dx = x2 - x1;
float dz = z2 - z1;
if (std::fabs(dz) > 0.0f) { // Or an epsilon instead of 0.0
float t = (z1 - z) / dz;
float newX = x1 + t * dx;
float newZ = z1 + t * dz;
}
Typed into post, so may or may not be correct.

Share this post


Link to post
Share on other sites
You calculate the slope by

m = (y2 - y1) / (x2 - x1)

To calculate the b-value, you put it an arbitrary point you know are on the line, with the m you know, and then solve for b.

y = m * x + b

b = y1 - m * x1

You now know the equation of the line. Now you wonder for which (x_ans, y_ans) the line intersects with a horizontal line y = z.
We express this as an equation and solve for x

z = m * x_ans + b

x_ans = (z - b) / m

So now we know the x for intersection, so we can easily get the y from the line equation:

y_ans = m * x_ans + b

Edit: Oh, stupid me, y_ans will of course always be equal to z, so you're done when you know x_ans.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!