You can rely on things like NGC or Sparky's collision plugins to deal with intersection tests.
However, as I like maths, I like writing my own simple tests. Here is my test for the intersection between a ray and a sphere.
Remstart
PJY - code to calculate intersection of ray (any 3d vector) and a sphere
Remend
sync on
sync rate 0
autocam off
type vec
x AS float
y AS float
z AS float
endtype
ray AS vec
circle_centre AS vec
result AS vec
repeat
ray.x = rnd(100)
ray.y = rnd(100)
ray.z = rnd(100)
circle_centre.x = rnd(1000)
circle_centre.y = rnd(1000)
circle_centre.z = rnd(1000)
circle_radius = rnd(150)
cls
temp = ray_sphere_intersect(ray, circle_centre, circle_radius)
if temp = 1
for i = 1 to 30
text 0, 0, "Result: " + str$(result.x) + " " + str$(result.y) + " " + str$(result.z)
text 0, 30, "Intersection? " + str$(temp)
sync
next i
endif
until returnkey() > 0
Rem PJY - function to calculate if the ray intersects with the circle
Rem PJY - if there is an intersection, the function returns a 1 and puts the
Rem PJY - coordinates of the intersection into "result"
function ray_sphere_intersect(ray AS vec, circle_centre AS vec, circle_radius AS integer)
null = make vector3(1)
null = make vector3(2)
Rem PJY - this vector is the ray
set vector3 1, ray.x, ray.y, ray.z
normalize vector3 1, 1
set vector3 2, circle_centre.x - ray.x, circle_centre.y - ray.y, circle_centre.z - ray.z
a_length# = dot product vector3(2, 1)
e_length# = length vector3(2)
b_length# = sqrt((e_length# * e_length#) - (a_length# * a_length#))
test_intersection# = (circle_radius * circle_radius) - (e_length# * e_length#) + (a_length# * a_length#)
Rem PJY - if test_intersection# is negative, there is no intersection
if test_intersection# => 0
f_length# = sqrt(test_intersection#)
t_dist# = a_length# - f_length#
multiply vector3 1, t_dist#
success = 1
result.x = x vector3(1)
result.y = y vector3(1)
result.z = z vector3(1)
else
success = 0
result.x = 0
result.y = 0
result.z = 0
endif
null = delete vector3(1)
null = delete vector3(2)
endfunction success
Cheer if you like bears! Cheer if you like jam sandwiches!
"I highly recommend Philip" (Philip)