$ git show spring-chain
Spring chain
Drag the lead bubble and a trail of smaller ones follows, each springing after the one in front of it.
// Unchanged in Reanimated 4: derived values with springs chain the same way
const COUNT = 6;
const leaderX = useSharedValue(START.x), leaderY = useSharedValue(START.y);
const pan = Gesture.Pan()
.onChange((e) => { leaderX.value += e.changeX; leaderY.value += e.changeY; });
// A custom hook can't run in a loop, so the chain is built from fixed calls
function useFollow(x, y) {
const fx = useDerivedValue(() => withSpring(x.value, { damping: 14, stiffness: 120 }));
const fy = useDerivedValue(() => withSpring(y.value, { damping: 14, stiffness: 120 }));
return [fx, fy];
}
const d1 = useFollow(leaderX, leaderY);
const d2 = useFollow(...d1);
const d3 = useFollow(...d2);
const d4 = useFollow(...d3);
const d5 = useFollow(...d4);
const chain = [[leaderX, leaderY], d1, d2, d3, d4, d5];
function Dot({ x, y, index }) {
const style = useAnimatedStyle(() => ({
transform: [{ translateX: x.value }, { translateY: y.value }, { scale: 1 - index * 0.12 }],
opacity: 1 - index * 0.12,
}));
return <Animated.View style={[styles.dot, { zIndex: COUNT - index }, style]} />; // absolute 36 x 36 circle
}
<GestureDetector gesture={pan}>
<View style={StyleSheet.absoluteFill}>
{chain.map(([x, y], i) => <Dot key={i} x={x} y={y} index={i} />)}
</View>
</GestureDetector>