Bouncing ball
A speech bubble that follows a moving object and stays visible at the edges of its field.
Demo
Try this: Press Play. A speech bubble with the number of bounces follows the ball. At the top edge the bubble jumps below the ball, at the left and right edge it slides along the wall. Press Pause and use Step to move the ball one tick at a time.
Calculated values
How it works
- The speech bubble is the item, the ball is the target, and the box is the boundary. The ball moves, the bubble follows.
-
itemAt: "bottom center"andtargetAt: "top center"put the bubble centered above the ball.targetOffset: { x: 0, y: -8, mirror: true }leaves a gap of 8 px. Withmirror, the gap stays when the bubble flips below the ball. -
flip: "both"handles the top edge: the bubble goes below the ball. At the left and right edge, flipping does not help, because a centered bubble is centered after the flip as well. -
stick: "all"handles that case. It pulls the bubble back inside the box, so it slides along the wall while the ball touches the wall. -
The loop calls
calculate()after every move of the ball. It does not callresize(), because the bubble keeps its size, andcalculate()reads the current positions of the ball and the box. The example removes thetransformof the bubble first, becausecalculate()starts from where the bubble is now. - The example starts paused, so a moving object does not start without a request. Play and Pause control the loop, and Step moves the ball by one tick.
Variations
-
In the playground, set
stickto"none": at the left and right edge the bubble leaves the box. -
Set
itemAtto"bottom left"andtargetAtto"top right"for a bubble above and to the right of the ball instead of centered above it.