Would like to create a mouse trail for a website, I am struggling with type script, is there a simple script that can track the position of the mouse to allow an object to follow it, regardless of clicking, so not dragging an object, but just an object linked to the mouses position
import { Behaviour, serializable, setWorldPosition } from "@needle-tools/engine";
import { Object3D, Vector3 } from "three";
export class PointerFollower extends Behaviour {
@serializable(Object3D)
object!: Object3D;
@serializable()
offset: number = 10;
update(): void {
const cam = this.context.mainCamera!;
const input = this.context.input;
// get relative mouse position, in range -1 to 1
const mouse = input.mousePositionRC;
// get world position of mouse on the near plane
const wPos = new Vector3(mouse.x, mouse.y, -1).unproject(cam!);
// caulculate direction from camera to world mouse
const dir = wPos.clone().sub(cam.position).normalize();
// offset it to the wanted distance
wPos.addScaledVector(dir, 10);
// apply the result
setWorldPosition(this.object, wPos);
}
}
Also for best performance, reuse vector variables and do not create as much garbage. Although such optimalization shouldn’t be noticeable on small applications.