Home > OS >  Chain multiple animations within loop
Chain multiple animations within loop

Time:12-20

I am trying to chain two animations together in an animation loop. First the text moves left, and then I want to get back to its original position with another animation.

I tried to add a callback within the Animated.timing within moveRight() but that didn't work.

Here is the code I have now. Basically I'm just trying to paste togeher moveRight() and moveLeft().

export default function App() {
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const secondFadeAnim = useRef(new Animated.Value(100)).current;

  const moveRight = () => {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 5000
    }).start();
  }

  const moveLeft = () => {
    Animated.loop(
      Animated.timing(fadeAnim, {
        toValue: -250,
        duration: 5000
      })).start();}
  
  


  const title = "This is some super long title it just keeps on going"
  


  return(
    <SafeAreaView style={styles.container}>
      <View style={styles.bord}>
        <Animated.View
          style={{
            transform: [{translateX: fadeAnim}]
          }}
        >
          <Text
          style={styles.title}
          >
           {title}
          </Text>
        </Animated.View>
                <Animated.View
          style={{
            transform: [{translateX: fadeAnim}]
          }}
        >
          <Text
          style={styles.title}
          >
          </Text>
        </Animated.View>
      </View>
      {moveLeft()}
    </SafeAreaView>
  );
}

CodePudding user response:

If I understand correctly, what you're trying to achieve is to make your text move in loop, going left, then right, then left...

If that's the case, you should be able to do this by composing some smaller animations.

Also, if you want to trigger your animation right after the component is rendered, you should be putting it inside an useEffect.

So, refactoring your animation, and putting it in a useEffect:

// ...
useEffect(() => {
    const moveRight = Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 5000,
    });
    
    const moveLeft = Animated.timing(fadeAnim, {
      toValue: -250,
      duration: 5000,
    });

    Animated.loop(Animated.sequence([moveLeft, moveRight]), -1).start();
  }, [fadeAnim]);
// ...

Basically, we are creating a infinite loop of a sequence of two animations: moveLeft and moveRight.

Hope this helps!

  • Related