Build a Cuddle Creature Adoption Center (Source Code)
A mini virtual pet that reacts to mouse proximity, follows the cursor, purrs, and falls asleep when idle.
Table of Contents
Letโs build a tiny virtual pet! The pet will read mouse coordinates to face and gently follow the cursor. If the mouse doesnโt move for 5 seconds, the pet falls asleep and emits โZzzโ bubbles.
Mouse Awareness
By calculating the Math.atan2 between the center of the pet and the mouse cursor, we can elegantly transition the petโs rotation to face the mouse.
let isSleeping = false;
let idleTimer;
window.addEventListener('mousemove', (e) => {
clearTimeout(idleTimer);
wakeUpPet();
// Calculate angle for eyes to look at mouse
const rect = pet.getBoundingClientRect();
const angle = Math.atan2(e.clientY - rect.top, e.clientX - rect.left);
pupils.forEach(p => p.style.transform = `rotate(${angle}rad) translateX(3px)`);
idleTimer = setTimeout(() => {
isSleeping = true;
fallAsleep();
}, 5000);
});
Head over to the Live Demo to adopt your own little creature and watch its adorable reactions!