0

I'm building a shooter in three.js in which spheres appear that the user must shoot. After shooting a sphere, the object disappears and another sphere pops up. I'm using Pointer Lock Controls.

I detect when a sphere gets shot using:

            function onDocumentMouseDown( event ) {
                var mouse3D = new THREE.Vector3();
                var raycaster = new THREE.Raycaster();
                mouse3D.normalize();
                controls.getDirection( mouse3D );
                raycaster.set( controls.getObject().position, mouse3D );
                var intersects = raycaster.intersectObjects( objects );
                // Change color if hit sphere
                if ( intersects.length > 0 ) {
                    intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
                    //hide shpere
                    object.traverse(function(child){child.visible = false;});
                    update_sphereplace();
                }
            }

This works perfectly, but now I want to integrate an accuracy feature. How could I track the accuracy based on the center of the sphere? So for example hitting the center should give me an accuracy of 100. Hitting the sphere relatively far from the center should give an accuracy near to 0 (but not 0, since 0 would be missing the sphere).

binoculars
  • 2,226
  • 5
  • 33
  • 61
  • Tip: Create one `Raycaster` and [reuse it](http://stackoverflow.com/questions/29311875/three-js-pointerlockcontrols-shooting-along-y-axis/29312773#29312773). – WestLangley May 15 '16 at 18:43
  • Thanks for the suggestion. How would this work? Do I just put `var raycaster = new THREE.Raycaster();`outside the `onDocumentMouseDown` function, or is there more to it? – binoculars May 15 '16 at 18:44

1 Answers1

0

You need to know by how much the ray misses the center of the sphere mesh.

var missDistance = raycaster.ray.distanceToPoint( intersects[ 0 ].object.position );

You then need to map that value to a score -- something like:

var score = 100 * Math.max( 1 - ( missDistance / sphereRadius ), 0 );

three.js r.76

WestLangley
  • 102,557
  • 10
  • 276
  • 276