Raycaster from Object3D's position down not finding my ground plane?

Hi! OK so I have a scene with 120 randomly generated Object3D’s (the trees and vegetation you’ll see in a second). Those are approximately placed above the ground (which is slanted) and so I’d like to make a raycaster loop to adjust their Y position so that they look nice and flush on the ground plane.

I’ve been on this for well over an hour and I’ve read at least 20 different threads about raycasting on various sites, including this one, but no solution I’ve read works for me. There are ZERO error in the console, the app works fine, no crash or nothing but there’s something I really don’t understand in how to use the Raycaster because it doesn’t find SH!T.

Here is a piece of code I have at the moment. The first paragraph draws a red vertical line where the raycaster should be aiming for, the second paragraph performs the actual raycasting and finally the third paragraph outputs the result in the console (and resumes my app, but right now this is useless because it never finds the ground plane at all). All I’m getting is 120 “Nope.” in the console and zero hit mesh.

function findIntersectionHeight(from_vec3, object_to_intersect){
				var testLineMaterial = new THREEJS.LineBasicMaterial({ color: 0xFF0000 });
				var points = [];
				points.push(new THREEJS.Vector3(from_vec3.x, from_vec3.y + 10, from_vec3.z));
				points.push(new THREEJS.Vector3(from_vec3.x, from_vec3.y - 10, from_vec3.z));
				var geometry = new THREEJS.BufferGeometry().setFromPoints(points);
				var line = new THREEJS.Line(geometry, testLineMaterial);
				scene.add(line);
				
				var raycaster = new THREEJS.Raycaster(new THREEJS.Vector3(from_vec3.x, from_vec3.y + 2, from_vec3.z), new THREEJS.Vector3(0, -1, 0));
				var intersects = raycaster.intersectObject(object_to_intersect);
				
				if(intersects.length > 0){
					console.log(intersects.length, intersects[0].object.name, intersects[0].point.y);
					return intersects[0].point.y;
				}
				else{
					console.log('Nope.');
					return from_vec3.y;
				}
			}

Here is how I call this function, “o” is the current Object3D to process in the loop:

o.position.setY(findIntersectionHeight(o.position, scene.getObjectByName(‘GroundPlane’)));

… and yes, scene.getObjectByName(‘GroundPlane’) returns an Object3D and I can toggle its visibility in the console and it’s the correct mesh, it’s the slanted ground plane in green below.

Please hit me with questions! I BEG YOU :wink: Thanks :slight_smile:

Got it fixed! This happens when you’re super tired. I had forgotten to call scene.updateMatrixWorld(); before doing raycasts, since adding all those random Object3D’s happens BEFORE the first render() loop. F*CK! :laughing:

I hope this helps somebody else in the future… perhaps even myself! :crazy_face:

Thanks to this guy, whoever he is: javascript - How to allow raycaster to intersect a plane buffer geometry in Three.js? - Stack Overflow