React Native Sensors - Гироскоп
Я использую гироскоп датчиков React Native, но не совсем понимаю, как он работает. Я реализовал шар, который поднимается и опускается в зависимости от наклона телефона (он поднимается, когда вы наклоняете камеру телефона к себе).
Но когда я играю с ним, мяч может иметь два разных положения при одинаковом наклоне.
Вы бы поняли почему? Вы найдете код ниже
import React, {useEffect, useState} from 'react'
import { View, Text, StyleSheet } from 'react-native'
import {gyroscope,
setUpdateIntervalForType,
SensorTypes}
from "react-native-sensors";
import Animated, {useDerivedValue, useSharedValue, useAnimatedStyle, withSpring} from 'react-native-reanimated'
import CountDown from 'react-native-countdown-component';
setUpdateIntervalForType(SensorTypes.gyroscope, 10);
const App = () => {
const [section, setSection] = useState(() => {return false})
const gyroValue = useSharedValue({x:0,y:0,z:0});
const prev = useSharedValue({x:0,y:0,z:0});
const deriveTranslations = useDerivedValue(() => {
const MAX_Y = 270;
let newY = prev.value.y+12*(Math.floor(10*gyroValue.value.x)/10);
if (Math.abs(newY) >= MAX_Y) {
newY = prev.value.y
}
if (Math.abs(gyroValue.value.x) <= 0.05) {
newY = prev.value.y
}
prev.value = {
y: newY
}
return (
{y: newY}
)
})
useEffect(() => {
const subscription = gyroscope.subscribe(({x,y,z}) => {
gyroValue.value = {x,y,z}
})
}, [prev.value]);
const AnimatedStyle = {
motion: useAnimatedStyle(() => {
return({
transform: [
{
translateY: withSpring(deriveTranslations.value.y),
},
],
flex:1,
justifyContent: 'center',
alignItems: 'center'
})
})
}
return (
<Animated.View style={AnimatedStyle.motion}>
<View style={styles.test}>
<Text> Coucou </Text>
</View>
</Animated.View>
)}
const styles = StyleSheet.create({
test: {
backgroundColor: 'red',
height: 70,
width: 70,
borderRadius: 70,
justifyContent: 'center',
alignItems: 'center'
},
main: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
export default App