I’ve always loved cracking open fortune cookies to see the surprise message inside. I decided to recreate this idea digitally by building an animated, interactive fortune cookie in p5.js that reveals a new quirky fortune each time it’s clicked.
The core concept here was to display random fortunes generated from a list of silly phrases. I started by coming up (with the help of ChatGPT) with a whole array of potential fortune texts – things like “Run” or “Don’t eat the paper.” I tried to channel the cryptic non-sequiturs you might find in real fortune cookies.I then set up a pickNewFortune() function that can select a random element from this master list of fortunes. This gets called every time the cookie finishes its opening animation.
So on each cookie click, it grabs a new random index from the list and stores this fortune string to display.
The visual animation of the cookie opening was also really fun to build out. I made the separate cookie halves tilt back and apart slowly to reveal the text underneath. I’m really happy and proud with how realistic the motion looks!
The code for the animation looks like this:
function animateCookie() { let halfAnimationStep = maxAnimationStep / 2; let angleOffset, pullOffset; if (animationStep <= halfAnimationStep) { // Tilt cookie halves apart angleOffset = map(animationStep, 0, halfAnimationStep, 0, -40); pullOffset = 0; } else { // Finish opening animation angleOffset = -40; pullOffset = map(animationStep, halfAnimationStep, maxAnimationStep, 0, 200); } drawFortuneCookie(angleOffset, pullOffset); // Progress animation if (animationStep < maxAnimationStep) { animationStep++; } else { state = 'open'; } }
In the future I could definitely expand and refine this concept even more – perhaps allowing the fortune text itself to animate in different ways for some visual variety. I would also love to enhance the text generation further – for example, mixing and matching fortune text fragments to assemble new combinations. I could also display the text animating onto the screen for more visual interest when the fortune is revealed.