Mouse position

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

Original Post on Discord

by user 618406875809054731

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);
    }
}

opera_N7KkSO0ozo.mp4

There’s an unproject function on Vector3 that helps you get the world position fro relative coordinates.

Also for best performance, reuse vector variables and do not create as much garbage. Although such optimalization shouldn’t be noticeable on small applications.

Ah thank you for this, it helped a lot

by user 618406875809054731