Super long ray efficiency

So I’m using whitelist {workspace.Terrain} to get maximum terrain height at a X,_,Z coordinate.
I think ray cost is product of the quantity of geometry which is dictated by the number of baseParts and the regions culled for scanning determined by the ray size itself.

I want to know if it is ok to do several long ray scans a frame to just the Terrain object? (1000 length, 60FPS * 8 to 70 rays

1 Like

I don’t think that raycasting would be an efficient solution to finding the maximum height. You can create a little algorithm with Terrain:ReadVoxels() instead, a must faster method.

1 Like

Yes but how inefficient is the case of just scanning terrain with a long ray? If I ever need to use it in the future for the normal, you recommend I use this algorithm to find the highest cell, and then just shoot a short ray down to its surface for that?
A much faster method in relation to an already acceptably fast method is not of personal concern, which I figure is the likely but uncertain case for this instance of raycasting.

While ray length does noticeably impact the performance, the presence of terrain seems to be a non-significant issue.

I ran a timed benchmark test with the following code to see if terrain and ray lengths would affect the overall performance:

wait(8)
local sum = 0
for o=1,50 do
	
local t=  tick()
for i=1,60*70 do
	
	workspace:FindPartOnRay(Ray.new(Vector3.new(math.random()*1000,2000,math.random()*1000),Vector3.new(0,-2000,0)),nil,true)
end
	
	sum = sum + tick()-t
--print(tick()-t)

end
print(sum/50)
wait()
local sum = 0
for o=1,50 do
	
local t=  tick()
for i=1,60*70 do
	
	workspace:FindPartOnRay(Ray.new(Vector3.new(math.random()*1000,300,math.random()*1000),Vector3.new(0,-300,0)),nil,true)
end
	
	sum = sum + tick()-t
--print(tick()-t)

end
print(sum/50)

It’s randomized to prevent possible result caching, and it averages the result of 50 iterations of 4200 iterations of 1000 stud and 300 stud ray casts, so the data below reflects the results of 4200 iterations on average.

When run on a world with only a single baseplate, the following results are (for 1000 stud and 300 stud respectively):

0.18865569591522
  0.037233214378357

When run on a world with a 1024x1024x1024 generated terrain, the following results are:

0.18400784492493
  0.043346810340881

Since doing 4200 ray casts on terrain appears to run virtually the same as on an empty baseplate, you’re good to go on terrain, its only the length that matters.

This is very considerate work and serves as a good resource. Thank you!

Keep in consideration I am not using FindPartOnRay. I still assume this should give the exact result for when I intend on using WhiteList with any number of parts.