I am trying to create a sphere with particles filled on its surface. It will move depends on the position on mousemove.
Strangely, it is not displayed on my webpage. I do see the div in the elements in developer tool.
I have tried:
- add camera to scene
- increase camera distance
camera.position.z
- change background color with
setClearColor()
- increase the size of particles on the sphere
useEffect(() => {
const scene = new THREE.Scene();
document.addEventListener("mousemove", onMouseMove, false);
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
let mouseX;
let mouseY;
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor(0xffffff, 1);
renderer.setSize(window.innerWidth, window.innerHeight);
sphereRef.current.appendChild(renderer.domElement);
window.addEventListener("resize", function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
const distance = Math.min(200, window.innerWidth / 4);
const geometry = new THREE.BufferGeometry();
for (let i = 0; i < 1600; i++) {
var vertex = new THREE.Vector3();
// var theta = THREE.Math.randFloatSpread(360);
var theta = Math.acos(THREE.Math.randFloatSpread(2));
var phi = THREE.Math.randFloatSpread(360);
vertex.x = distance * Math.sin(theta) * Math.cos(phi);
vertex.y = distance * Math.sin(theta) * Math.sin(phi);
vertex.z = distance * Math.cos(theta);
geometry.setFromPoints(vertex);
geometry.computeVertexNormals();
}
//setting particles color and size
var particles = new THREE.Points(
geometry,
new THREE.PointsMaterial({ color: 0x000000, size: 5 })
);
particles.boundingSphere = 50;
//adding particles to group for sphere
var renderingParent = new THREE.Group();
renderingParent.add(particles);
var resizeContainer = new THREE.Group();
resizeContainer.add(renderingParent);
scene.add(resizeContainer);
camera.position.z = 200;
scene.add(camera);
var animate = function () {
requestAnimationFrame(animate);
renderer.render(scene, camera);
};
function onMouseMove(event) {
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
myTween = gsap.to(particles.rotation, {
duration: 0.1,
x: mouseY * -1,
y: mouseX,
});
}
animate();
return () => sphereRef.current.removeChild(renderer.domElement);
})
<div className="sphere" id='sphere' ref={sphereRef}></div>