How do i add click event to a mesh?

So i make a sun, and i want to add a click event to my mesh, how do i do that?

import { renderer } from "../utils/renderer";
import { scene } from "../utils/scene";
import { camera } from "../utils/camera";
import * as THREE from "three";
import { sun } from "../components/sun";

const light = new THREE.PointLight(0xffffff);
const ambientLight = new THREE.AmbientLight(0x222222);
light.position.set(-50, 5, 5);
camera.position.z = 900;
camera.position.x = 100;
sun.position.x = -900;

const lightHelper = new THREE.PointLightHelper(ambientLight);

function animate() {
  sun.rotation.y += 0.002;
  renderer.render(scene, camera);

You might want to start from studying ray casting examples:

this will add an extra condition that your mouse is hovering over the mesh, the rest can be done as a normal mouse click event on the canvas.

if it’s really just a click tie raycaster to your mesh. anything more than that can quickly throw you into a lot of churn. real pointer events require some kind of state management and implementations are anything but trivial. i have a basic implementation of click/over/out here Basic Threejs example with re-use - CodeSandbox

by that point you probably realize that this can only result in a mess as oop + classes quickly reach their limits. pair threejs to a framework and you get real pointer events just like you use them on the dom: Basic React example with re-use - CodeSandbox

there are vanilla alternatives like GitHub - markuslerner/THREE.Interactive: Fast and simple interaction manager for three.js for enabling mouse and touch events on 3D objects but the downside is that, sadly, few people use it, know about it, or help maintain it. i wonder why since packages like that are invaluable.

1 Like

thanks for the heads up, i will try some of your solution right now! thanks for your help