Page 1 of 1

Point where a line segment intersects a sphere?

Posted: Fri Nov 27, 2020 10:07 am
by ExpEM
Can anyone please help me out with this please?

Code: Select all

(Global) Var Vector Intersect1, Intersect2;

Function Int FindSphereIntersection(Vector LineStart, Vector LineEnd, Vector SphereOrigin, Float SphereRadius)
{
	//Math, math, math.
	//Math, math, math.
	//Math, math, math.
	
	if (Line from LineStart to LineEnd doesnt intersect with Sphere)
		Return 0;
		
	if (Line from LineStart to LineEnd intersects with Sphere once)
	{
		Intersect1 = Intersect point;
		Return 1;
	}
	
	if (Line from LineStart to LineEnd intersects with Sphere twice)
	{
		Intersect1 = Intersect point;
		Intersect1 = Other intersect point;
		Return 2;
	}
}
This sort of math is beyond my understanding unfortunately so any help would be appreciated thanks.

Re: Point where a line segment intersects a sphere?

Posted: Fri Nov 27, 2020 2:30 pm
by Bleeder91[NL]
I'm too tired to code it now but this might help:
https://www.scratchapixel.com/lessons/3 ... tersection

Re: Point where a line segment intersects a sphere?

Posted: Fri Nov 27, 2020 10:25 pm
by .:..:
I've used this code for 2D sphere ray to sphere collision check, pretty sure it works just like that in 3D coordinates too:

Code: Select all

simulated function TraceActor( TDActor A, TR_TraceInfo T )
{
	local float aa,b,c,radii;
	local vector Dir;

	Dir = T.Start - A.Location2D;
	radii = A.CollisionSize.X + T.Extent.X;

	// Simple circle overlap check.
	c = (Dir Dot Dir) - Square(radii);
	if( c<0.f )
	{
		Dir = Normal(Dir);
		if( (Dir Dot T.Dir)<0.1f ) // Only allow to exit from the circle.
			T.SetTraceHit(A,0.f,Dir);
		return;
	}

	aa = T.Dir Dot T.Dir;
	b = 2.f * (Dir Dot T.Dir);

	radii = Square(b) - 4.f*aa*c;
	if( radii < 0 )
	{
		// no intersection
		return;
	}

	// ray didn't totally miss sphere,
	// so there is a solution to
	// the equation.
	// radii = Sqrt( radii );

	// either solution may be on or off the ray so need to test both
	// t1 is always the smaller value, because BOTH discriminant and
	// a are nonnegative.
	c = (-b - Sqrt( radii ))/(2.f*aa);

	if( c >= 0 && c <= 1 )
		T.SetTraceHit(A,c,Normal(T.Start+T.Dir*c-A.Location2D));
}
To help understand the values:
T.Start = trace start.
A.Location2D = sphere location.
A.CollisionSize.X = sphere radius.
T.Extent.X = ray trace sphere radius.
T.Dir = End-Start direction of raytrace.
T.SetTraceHit(<hit actor>,<hit time in range 0-1>,<hit normal>);

As said it was originally only used for 2D traces, but it should work in 3D too.

Re: Point where a line segment intersects a sphere?

Posted: Sat Nov 28, 2020 8:51 am
by ExpEM
Thank you both for your help!

I have a solution here: https://ut99.org/viewtopic.php?f=15&t=1 ... 22#p124822