Works by

Ren's blog

@rennnosuke_rk 技術ブログです

【React Native】Expoで加速度センサを使う

Accelerometer

React Nativeでの加速度実装ですが、ネイティブで標準実装できる範囲内なので特別なパッケージを入れずとも実装できます。
Expoパッケージの加速度計測モジュールが簡単だったので、今回はこちらを紹介します。

Accelerometer - Expo Documentation

Usage

create-react-native-appでプロジェクトを作成します。
この時点でExpoパッケージは入っているので、他のインストール作業は不要です。

$ create-react-native-app react-native-acceleromator-app

Source

参考: Accelerometer - Expo Documentation

<feff>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Accelerometer } from 'expo';

export default class App extends React.Component {

  constructor() {
    super();
    // state初期化
    this.state = {
      accelerometerData: {}
    };
  }

  componentDidMount() {
    this._toggle();
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  _toggle = () => {
    if (this._subscription) {
      this._unsubscribe();
    } else {
      this._subscribe();
    }
  }

  // 加速度センシングを開始する
  _subscribe = () => {
    this._subscription = Accelerometer.addListener(accelerometerData => {
      // 加速度を取得
      this.setState({ accelerometerData });
    });
    // 1秒ごとに加速度を測定
    Accelerometer.setUpdateInterval(1000);
  }

  // 加速度センシングを終了する
  _unsubscribe = () => {
    if (this._subscription) {
      this._subscription.remove();
    }
    this._subscription = null;
  }

  render() {
    let { x, y, z } = this.state.accelerometerData;
    return (
      <View style={styles.container}>
        <Text>x : {x}</Text>
        <Text>y : {y}</Text>
        <Text>z : {z}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Accelerometerを利用すればリスナーを登録するだけで簡単に実装できます。
加速度計測を終了したいときは、setListenerの返戻オブジェクトのremove()オブジェクトを呼べばOKです。

Demo

f:id:rennnosukesann:20180606224157g:plain:w300

加速度が取得できました。
端末のジェスチャーやゲーム実装に使えそうです。

参考

Accelerometer - Expo Documentation