When attempting to draw an arrow from one mesh object to another, I encountered some issues. Directly using the positions of the objects as arguments in the Arrow Helper resulted in the arrow going inside the object due to the position representing the center of the object.
To resolve this, I decided to create objects and utilize raycasting.
var ray = new THREE.Raycaster(sourcePos, direction.clone().normalize());
In this setup, the origin is set as the source object's position and the direction is determined from the source to the target. By intersecting with the target, I obtain collision results:
var collisionResults = ray.intersectObject(target);
The next step involves calculating the distance at which the ray first intersects the target:
var length = collisionResults[0].distance;
Finally, an arrow is created using the calculated values:
var arrow = new THREE.ArrowHelper(direction.clone().normalize(), sourcePos, length, 0xaa0000);
scene.add(arrow);
The arrow creation process works well for certain cases like:
helper_methods.draw_arrow(mesh1, mesh2);
helper_methods.draw_arrow(mesh1, mesh2);
However, when trying to draw an arrow between mesh2 and mesh3:
helper_methods.draw_arrow(mesh2, mesh3);
An error message stating "collisionResults[0] is null" is displayed. I am currently unable to identify the root cause of this issue and would appreciate any assistance. Below is a snippet of the code being used along with the helper methods:
var mesh1 = helper_methods.create_mesh();
mesh1.position.set(100, 0, 0);
scene.add(mesh1);
var mesh2 = helper_methods.create_mesh();
mesh2.position.set(300, 0, 0);
scene.add(mesh2);
var mesh3 = helper_methods.create_mesh();
mesh3.position.set(100, 200, 0);
scene.add(mesh3);
helper_methods.draw_arrow(mesh1, mesh2);
helper_methods.draw_arrow(mesh1, mesh2);
helper_methods.draw_arrow(mesh2, mesh3);
Below are the helper methods used in the code:
create_mesh: function(){
var darkMaterial = new THREE.MeshBasicMaterial({color: 0xffffcc});
var geometry = new THREE.CylinderGeometry(30, 30, 50, 100, 1);
var mesh = new THREE.Mesh(geometry, darkMaterial);
return mesh;
},
draw_arrow: function(source, target){
var sourcePos = new THREE.Vector3(source.position.x, source.position.y, source.position.z);
var targetPos = new THREE.Vector3(target.position.x, target.position.y, target.position.z);
var direction = new THREE.Vector3().subVectors(targetPos, sourcePos);
var ray = new THREE.Raycaster(sourcePos, direction.clone().normalize());
var collisionResults = ray.intersectObject(target);
var length = collisionResults[0].distance;
var arrow = new THREE.ArrowHelper(direction.clone().normalize(), sourcePos, length, 0xaa0000);
scene.add(arrow);
return arrow;
}