I have a scene which takes on the form of a sphere, representing the Earth, with a collection of points in orbit. I now want to be able to click on a given point and get its index, but I am having trouble getting it working.
I am looking at other questions, but I don’t seem to be working out the missing piece of the puzzle.
The camera and scene are setup as follows:
this.scene = new SatelliteOrbitScene();
this.camera = new PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 );
this.renderer = new WebGLRenderer({ antialias: false });
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(window.innerWidth, window.innerHeight);
document
.querySelector(this.config.canvasSelector)
?.appendChild(this.renderer.domElement);
this.controls = new OrbitControls( this.camera, this.renderer.domElement );
this.camera.position.set( 15, 0, 10000 );
this.controls.update();
this.raycaster = new Raycaster();
The points are set up as follows:
const geometry = new BufferGeometry();
const vertices: Float32Array = new Float32Array();
const sizes: Float32Array = new Float32Array();
const colors: number[] = [];
vertices.fill(0, 0, this.satelliteStore.satData.length * 3);
colors.fill(0, 0, this.satelliteStore.satData.length * 3);
sizes.fill(10, 0, this.satelliteStore.satData.length);
geometry.setAttribute('position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute('color', new Float32BufferAttribute( colors, 4 ) );
geometry.setAttribute('size', new Float32BufferAttribute( sizes, 1 ) );
const texture = new TextureLoader().load(`${this.baseUrl}/images/circle.png`);
const shader = this.shaderStore.getShader('dot2');
const material = new ShaderMaterial({
uniforms: {
color: { value: new Color( 0xffffff ) },
pointTexture: { value: texture }
},
clipping: true,
vertexShader: shader.vertex,
fragmentShader: shader.fragment,
blending: AdditiveBlending,
depthTest: true,
transparent: true
});
Then trying to handle the click:
const canvasElement = this.renderer.domElement;
canvasElement.addEventListener('click', (event:MouseEvent) => {
if (!this.raycaster || !this.scene) {
return;
}
const bounds = canvasElement.getBoundingClientRect();
const mouse: Vector2 = new Vector2();
mouse.x = ( (event.clientX - bounds.left) / canvasElement.clientWidth ) * 2 - 1;
mouse.y = - ( (event.clientY - bounds.top) / canvasElement.clientHeight ) * 2 + 1;
this.raycaster.setFromCamera( mouse, this.camera as PerspectiveCamera);
const intersects = this.raycaster.intersectObjects(this.scene.children, true);
if (intersects.length > 0) {
console.log('>>>', intersects);
// Do stuff
}
});
When I look at the value of intersects
I am not seeing anything that would let me know the point that was clicked.
Can anyone suggest where I’m going wrong?
BTW the project code: GitHub - ajmas/StuffInSpace at issue-1-threejs