How to use Gyroscope

Reading Time: 4 minutes

One of the most used features in mobiles is the use of gyroscopes; it is used in several applications, such as Pokemon Go, floating compass, and other apps. Keep reading to know how to use Gyroscopes with animations.

How to use Gyroscope with animation

Gyroscope is a sensor that measures non-gravitational acceleration and it is intended to complement the information about the orientation of the mobile provided by the accelerometer. For that, it adds a fourth dimension of movement which measures the rotation or spinning of the mobile.

React Native Sensors

It is a library created for apps that need the mobile’s rotation/spinning. It provides you with:

  1. Accelerometer: provides access to the device’s accelerometer sensor(s) and associated listeners to respond to changes in acceleration in 3D space, meaning any movement or vibration.

  2. Gyroscope: provides access to the device's gyroscope sensor to respond to changes in rotation in 3D space.

  3. Magnetometer: provides access to the device’s magnetometer sensor(s) to respond and measure changes in the magnetic field. You can access the calibrated values with it.

  4. Barometer: provides access to the device’s barometer sensor to respond to changes in air pressure. Pressure is measured in hectopascals or hPa.

  5. setUpdateIntervalForType: The sensors are global; we can only set the rate in which the hardware is read globally. Please note that native platforms treat this more as a recommendation rather than an exact value.

However, we will only need to implement the gyroscope in our application.

Installation

$ npm install react-native-sensors --save

Automatic installation

$ react-native link react-native-sensors

Option: With CocoaPods (iOS only)

Add the following to your Podfile and run $ pod install:
pod 'RNSensors', :path => '../node_modules/react-native-sensors'

If you have any doubts with the installation you can check the official documentation here.

Setup

Now let's start coding. First we have to import a gyroscope from the library.

import { gyroscope } from "react-native-sensors";

const subscription = gyroscope.subscribe(({ x, y, z, timestamp }) =>
  console.log({ x, y, z, timestamp })
);

Now we can use the gyroscope and its functions to obtain the values of x,y,z and the timestamp.

React Native reanimated

Reanimated is a React Native library that allows creating smooth animations and interactions that run on the UI thread.

Install

yarn add react-native-reanimated@next

Add Babel plugin
module.exports = { 
   plugins: [ 'react-native-reanimated/plugin',]
  , 
};

The configuration of Android and iOS is extensive, I will leave the link to the documentation here so that you can install it.

Getting started

Now we are going to start coding; we start by importing the dependencies, we import gyroscope by react-native-sensors library, while Animated by react-native-reanimated library to the JS file.

import React, {useEffect} from 'react';
import {SafeAreaView, View, Text, Image} from 'react-native';
import {gyroscope} from 'react-native-sensors';
import Animated, {
 Easing,
 interpolate,
 useAnimatedStyle,
 useDerivedValue,
 useSharedValue,
 withSpring,
} from 'react-native-reanimated';

Now in our app component we are going to create the current value of the gyroscope and the previous one using the hook useShareValue; this hook is to create a reference to a JavaScript value that can be shared with worklets. They can carry data, provide a way to react to changes, and also drive animations.

const App = () => {
 const gyroValue = useSharedValue({x: 0, y: 0, z: 0});
 const prev = useSharedValue({x: 0, y: 0});
 …

After this, we need to add the gyroscope configuration in useEffect.

useEffect(() => {
   const subscription = gyroscope.subscribe(({x, y, z, timestamp}) => {
     gyroValue.value = {x, y, z};
   });
   return () => {
     subscription.unsubscribe();
   };
 }, [gyroValue.value]);

Now we need to create a function to update the x and y values using useDerivadeValue. This hook allows creating shared value references that can change in response to the update of one or more shared values. We multiply the new values with a negative value to make them positive, and validate the maximum values of x and y in order to stay on the screen.

const derivedTranslations = useDerivedValue(() => {
   'worklet';
   const MAX_X = 540;
   const MAX_Y = 540;

   let newX = prev.value.x + gyroValue.value.y * -1;
   let newY = prev.value.y + gyroValue.value.x * -1;

   if (Math.abs(newX) >= MAX_X) {
     newX = prev.value.x;
   }
   if (Math.abs(newY) >= MAX_Y) {
     newY = prev.value.y;
   }
   prev.value = {
     x: newX,
     y: newY,
   };
   return {
     x: newX,
     y: newY,
   };
 }, [gyroValue.value]);

Now, we need to add the animation to put it in our view component, so we are going to use the x and y values of your gyroscope using useAnimatedStyle. This hook is one of the main elements of the new Reanimated v2 API. It allows creating an association between shared values and view properties.

const AnimatedStyles = {
   motion: useAnimatedStyle(() => {
     return {
       transform: [
         {
           translateX: withSpring(
             derivedTranslations.value.x
           ),
         },
         {
           translateY: withSpring(
             derivedTranslations.value.y
           ),
         },
       ],
     };
   }),
 };

Finally, we add the animated styles on the AnimatedView

return (
   <SafeAreaView
     style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
     <Image
       source={require('./src/components/images/tapete.jpeg')}
       style={{width: 400, height: 990, position: 'absolute'}} />
       <Animated.View style={AnimatedStyles.motion}>
         <PokerCard />
       </Animated.View>
   </SafeAreaView>
 );

Now we need to run the emulator and use the virtual sensors to test the app.

Take a look at the emulator:

Download Video Recording

To conclude

React Native sensors will help you a lot when you want to use the motion sensors of a cell phone, you can create motion menus, components, and video games, so get the most out of this library.

0 Shares:
You May Also Like
Read More

RegEx Basics Guide

Reading Time: 6 minutes This guide is a quick compilation of many Regular Expresions examples and how to use them to be…