Need help for Raycaster


I’m making a small web game that the submarine is cleaning up the ocean. However, I’m struggling with collision event. The result I want to show is that when the submarine touch a red box, message on the top will show “Hit”(If the result can be the red box disappear will be great). Therefore, I tried to use Raycaster to detect the boxes, but it doesn’t work. Because I’m a beginner of threejs, I can’t find out the problem with my code. Please help me check my code, thank you!

My game link:

Raycaster event code:

function update(){

	var originPoint = cabin.position.clone();

	for (var vertexIndex = 0; vertexIndex < cabin.geometry.vertices.length; vertexIndex++)
		var localVertex = cabin.geometry.vertices[vertexIndex].clone();
		var globalVertex = localVertex.applyMatrix4( cabin.matrix );
		var directionVector = globalVertex.sub( cabin.position );

		var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
		var intersects  = ray.intersectObjects( collidableMeshList );

		if ( intersects.length > 0 && intersects[0].distance < directionVector.length() ) {
			appendText(" Hit ");


Raycaster collision:

1 Like

I would not use raycasting in your game. Instead you can generate AABBs via Box3.setFromObject() for your submarine and red obstacles. Then you can use Box3.intersectsBox() for simple and fast collision detection.

If you have to update an existing AABB with the new transformation of the object, use Box3.applyMatrix4(). In general, the tightness of an AABB should be sufficient for your use case.


Can you explain more how Box3.setFromObject() works in my case? I have researched it but only see limited information about it. I’m not quit sure how to use it. Thank you!

You would create a bounding box for your submarine like this:

const aabb =  new THREE.Box3().setFromObject( submarine.mesh );

Since your obstacles all have the same geometry, create an additional AABB for them. In a for loop, you iterate over all obstacles, update the respective AABB so it matches the current transformation of the obstacle and then you perform the intersection test with the submarine’s AABB.