https://github.com/needle-tools/needle-engine-support/assets/30328735/92404e43-9d45-4ee2-a018-fb00412b6bd5
import { Behaviour, serializable, setWorldPosition } from "@needle-tools/engine";
import { Object3D, Vector3 } from "three";
const vector1 = new Vector3();
const vector2 = new Vector3();
export class PointerFollower extends Behaviour {
@serializable(Object3D)
target?: Object3D;
@serializable()
offset: number = 10;
update(): void {
const cam = this.context.mainCamera;
const input = this.context.input;
if(!this.target || !cam)
return;
// get relative mouse position, in range -1 to 1
const mouse = input.mousePositionRC;
// get world position of mouse on the near plane
vector1.set(mouse.x, mouse.y, -1).unproject(cam!);
// caulculate direction from camera to world mouse
vector2.copy(vector1).sub(cam.position).normalize();
// offset it to the wanted distance
vector1.addScaledVector(vector2, this.offset);
// apply the result
setWorldPosition(this.target, vector1);
}
}