@meganetaaan/mouse-follower
Version:
TypeScript library for creating animated sprites that smoothly follow mouse cursor or other targets using physics-based movement
86 lines (85 loc) • 2.01 kB
JavaScript
export class MouseTarget {
x = 0;
y = 0;
isTracking = false;
constructor() {
this.setupMouseTracking();
}
setupMouseTracking() {
if (!this.isTracking) {
window.addEventListener("mousemove", (e) => {
this.x = e.clientX;
this.y = e.clientY;
});
this.isTracking = true;
}
}
}
export class OffsetTarget {
target;
offsetX;
offsetY;
constructor(target, offsetX = 0, offsetY = 0) {
this.target = target;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
get x() {
return this.target.x + this.offsetX;
}
get y() {
return this.target.y + this.offsetY;
}
}
export const DEFAULT_ANIMATIONS = {
walk: {
start: [0, 0],
numFrames: 4,
repeat: true,
},
action: {
start: [0, 0], // Temporarily using same animation as walk
numFrames: 4,
repeat: false,
},
};
// Sprite presets
export function stackChanPreset() {
return {
url: new URL("../../assets/stack-chan.png", import.meta.url).href,
width: 32,
height: 32,
frames: 4,
transparentColor: "rgb(0, 255, 0)",
animation: {
interval: 125,
},
animations: {
walk: {
start: [0, 0],
numFrames: 4,
repeat: true,
interval: 100,
},
action: {
start: [0, 32], // Temporarily using same animation as walk
numFrames: 4,
repeat: false,
},
},
};
}
export const SPRITE_PRESET_STACK_CHAN = stackChanPreset();
export const DEFAULTS = {
physics: {
velocity: 400,
accel: 2000,
braking: {
stopDistance: 30,
distance: 200,
strength: 8.0,
minVelocity: 50.0,
},
},
sprite: stackChanPreset(),
};