Created
January 31, 2019 12:11
-
-
Save kirkness/4a0003dedb60bf80217c55a0950b77a3 to your computer and use it in GitHub Desktop.
React Native Reanimated Spring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { GestureHandler } from 'expo'; | |
import { View } from 'react-native'; | |
import Animated from 'react-native-reanimated'; | |
const { PanGestureHandler, State } = GestureHandler; | |
const { | |
event, | |
set, | |
eq, | |
cond, | |
clockRunning, | |
Clock, | |
Value, | |
stopClock, | |
startClock, | |
spring, | |
debug, | |
} = Animated; | |
const runSpring = (value, vel, dragState, axis) => { | |
const clock = new Clock(); | |
const state = { | |
finished: new Value(0), | |
velocity: new Value(0), | |
position: new Value(0), | |
time: new Value(0), | |
}; | |
const config = { | |
toValue: new Value(0), | |
damping: 7, | |
mass: 1, | |
stiffness: 121.6, | |
overshootClamping: false, | |
restSpeedThreshold: 0.001, | |
restDisplacementThreshold: 0.001, | |
}; | |
return cond(eq(dragState, State.END), [ | |
cond(clockRunning(clock), 0, [ | |
set(state.finished, 0), | |
set(state.time, 0), | |
set(state.position, value), | |
set(state.velocity, vel), | |
set(config.toValue, 0), | |
debug(`Start clock ${axis}`, startClock(clock)), | |
]), | |
cond( | |
state.finished, | |
debug(`Stop clock ${axis}`, stopClock(clock)), | |
), | |
spring(clock, state, config), | |
state.position, | |
], value); | |
}; | |
export default class Card extends React.Component { | |
translationX = new Animated.Value(0); | |
translationY = new Animated.Value(0); | |
velocityX = new Animated.Value(0); | |
velocityY = new Animated.Value(0); | |
dragState = new Value(0); | |
handleGestureEvent = event([ | |
{ | |
nativeEvent: { | |
velocityX: this.velocityX, | |
velocityY: this.velocityY, | |
translationX: this.translationX, | |
translationY: this.translationY, | |
state: this.dragState, | |
}, | |
}, | |
]); | |
position = { | |
x: runSpring(this.translationX, this.velocityX, this.dragState, 'X'), | |
y: runSpring(this.translationY, this.velocityY, this.dragState, 'Y'), | |
}; | |
render() { | |
return ( | |
<View style={{ | |
flex: 1, | |
backgroundColor: '#eee', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}} | |
> | |
<PanGestureHandler | |
onGestureEvent={this.handleGestureEvent} | |
onHandlerStateChange={this.handleGestureEvent} | |
> | |
<Animated.View | |
style={{ | |
height: '80%', | |
width: '80%', | |
backgroundColor: '#fff', | |
transform: [{ translateX: this.position.x, translateY: this.position.y }], | |
}} | |
/> | |
</PanGestureHandler> | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment