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.

How it works

  1. The speech bubble is the item, the ball is the target, and the box is the boundary. The ball moves, the bubble follows.
  2. itemAt: "bottom center" and targetAt: "top center" put the bubble centered above the ball. targetOffset: { x: 0, y: -8, mirror: true } leaves a gap of 8 px. With mirror, the gap stays when the bubble flips below the ball.
  3. 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.
  4. 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.
  5. The loop calls calculate() after every move of the ball. It does not call resize(), because the bubble keeps its size, and calculate() reads the current positions of the ball and the box. The example removes the transform of the bubble first, because calculate() starts from where the bubble is now.
  6. 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

See also