Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: AnimationValue.interpolate for sin and cos

I am trying to animate a component in ReactJS native so that it orbits continuously around a point in a circular fashion. Basically, I need a timer that continuously increases that I can use to set the X, Y coordinates as something like {x: r * Math.sin(timer), y: r * Math.cos(timer)}

I found this guide which has some really helpful information about interpolation but I am still not having any success:

http://browniefed.com/react-native-animation-book/INTERPOLATION.html

How can I update the position of my component like this?

Bonus question: How can I make the animation continuous?

like image 556
Mouscellaneous Avatar asked Sep 08 '26 13:09

Mouscellaneous


1 Answers

Since react-native interpolation doesn't support function callback, I made a helper function:

function withFunction(callback) {
    let inputRange = [], outputRange = [], steps = 50;
    /// input range 0-1
    for (let i=0; i<=steps; ++i) {
        let key = i/steps;
        inputRange.push(key);
        outputRange.push(callback(key));
    }
    return { inputRange, outputRange };
}

Apply animation to translateX and translateY:

transform: [
{
   translateX:
      this.rotate.interpolate(
         withFunction( (value) => Math.cos(Math.PI*value*2) * radius )
      )
},
{
   translateY:
      this.rotate.interpolate(
         withFunction( (value) => Math.sin(Math.PI*value*2) * radius )
      )
},
]

Visual result:

enter image description here

And to make animation continuous, I did something like this:

rotate = new Animated.Value(0);

componentDidMount() {
    setInterval( () => {
        let step = 0.05;
        let final = this.rotate._value+step;
        if (final >= 1) final = 0;
        this.rotate.setValue(final);
    }, 50);
}
like image 94
Val Avatar answered Sep 13 '26 00:09

Val



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!