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!