Here is the final of my recent series of postings of intersection and geometrical tests. This example demonstrates how to find the point on a plane closest to another point, as well as the distance between the two.
Remstart
PJY - code to calculate the closest point on a plane to another point outside
the plane
Remend
sync on
sync rate 40
autocam off
make object plain 1, 100, 100
set object light 1, 1
set object ambient 1, 1
d3d_init
type vec
x AS float
y AS float
z AS float
endtype
ray AS vec
plane_normal AS vec
result AS vec
reset = 1
repeat
if reset = 1
repeat
ray.x = rnd(40) - 20
ray.y = rnd(40) - 20
ray.z = rnd(40) - 20
plane_normal.x = rnd(10) - 5
plane_normal.y = rnd(10) - 5
plane_normal.z = rnd(10) - 5
null = make vector3(1)
set vector3 1, plane_normal.x, plane_normal.y, plane_normal.z
normalize vector3 1, 1
plane_normal.x = x vector3(1)
plane_normal.y = y vector3(1)
plane_normal.z = z vector3(1)
null = delete vector3(1)
temp# = closest_point_on_plane(ray, plane_normal)
position camera 0, result.x, result.y + 20, result.z - 100
point camera 0, result.x, result.y, result.z
reset = 0
until temp# > 0
endif
if temp# > 0
text 0, 0, "Result: " + str$(result.x) + " " + str$(result.y) + " " + str$(result.z)
text 0, 30, "Distance? " + str$(temp#)
d3d_dot3d ray.x, ray.y, ray.z, 5, rgb(255, 255, 0), 1
position object 1, 0, 0, 0
point object 1, plane_normal.x, plane_normal.y, plane_normal.z
d3d_line3d 0, 0, 0, plane_normal.x * 5, plane_normal.y * 5, plane_normal.z * 5, rgb(0, 255, 0), 1
d3d_dot3d result.x, result.y, result.z, 5, rgb(0, 0, 255), 1
control camera using arrowkeys 0, 2, 2
sync
endif
if spacekey() > 0
reset = 1
endif
until returnkey() > 0
flush video memory
end
Rem PJY - function to calculate the point on a plane closest to the point
Rem PJY - represented by ray. This function assumes plane_normal has been
Rem PJY - normalized before being passed into the function. It returns the
Rem PJY - distance between ray and the closest point on the plane
function closest_point_on_plane(ray AS vec, plane_normal AS vec)
null = make vector3(1)
null = make vector3(2)
set vector3 1, ray.x, ray.y, ray.z
set vector3 2, plane_normal.x, plane_normal.y, plane_normal.z
dist# = dot product vector3(1, 2)
Rem PJY - if dist# is negative, the ray is on the reverse side of the plane
scale vector3 2, 2, dist#
subtract vector3 2, 1, 2
result.x = x vector3(2)
result.y = y vector3(2)
result.z = z vector3(2)
null = delete vector3(1)
null = delete vector3(2)
endfunction dist#
Cheer if you like bears! Cheer if you like jam sandwiches!
"I highly recommend Philip" (Philip)