$ git show gyro-parallax
Gyroscope parallax
Layers of an illustration drift by different amounts as you tilt the phone, giving the picture depth.
// Unchanged in Reanimated 4: the sensor value still arrives on the UI thread
import { useAnimatedSensor, SensorType } from 'react-native-reanimated';
const sensor = useAnimatedSensor(SensorType.ROTATION, { interval: 16 });
function Layer({ depth, children }) {
const style = useAnimatedStyle(() => {
const { pitch, roll } = sensor.sensor.value; // radians
return {
transform: [
{ translateX: withSpring(clamp(roll, -0.6, 0.6) * depth * 40, { damping: 20 }) },
{ translateY: withSpring(clamp(pitch - 0.6, -0.6, 0.6) * depth * 40, { damping: 20 }) }, // 0.6 = phone held tilted
],
};
});
return <Animated.View style={[StyleSheet.absoluteFill, style]}>{children}</Animated.View>;
}
<View style={{ width: W, height: H, overflow: 'hidden', borderRadius: 20 }}>
<Layer depth={-0.3}><Image source={sky} style={styles.oversized} /></Layer>
<Layer depth={0.4}><Image source={mountains} style={styles.oversized} /></Layer>
<Layer depth={1}><Image source={foreground} style={styles.oversized} /></Layer>
</View>
// oversized: inset -40 so moving layers never show their edges