Create a Pokemon battle game with React Native - Part 3: Animations and sounds

  • Wern Ancheta
November 30th, 2018
You will need Node 8+, Expo and Yarn installed on your machine.

In this tutorial, we’ll add battle animations and sounds to make the game more fun to play with.

This is the final tutorial of a three-part series on creating a Pokemon battle game with React Native. These are the topics covered in this series:

Prerequisites

This tutorial has the same prerequisites as part two of the series.

Overview of features to add

Since we’ve already implemented most of the features of the app, we can now focus on aesthetics. In this part, we’ll add animations and sounds to make it more interesting and pleasing to play with.

Here are the sounds that we’re going to add:

  • Screen
  • Pokemon cry

Here are the animations that we’re going to implement:

  • Health bar
  • Pokemon moves

We’re going to add the sounds first before the animations, as they’re easier to implement.

We’ll be using the Audio API provided by Expo to play sounds, and React Native’s animation library to implement the animations.

Screen sounds

We’ll add background music to each of the screens. We’ll be using the sounds from khinsider.com. Specifically, we’ll use the following soundtracks:

Open the links above and download the .mp3 file. Create a sounds/background folder inside src/assets and copy the files you downloaded in there.

You can also copy the files from the repo.

Login screen background sound

Open the login screen file, and import the Audio package from Expo:

    // src/screens/LoginScreen.js
    import CustomText from "../components/CustomText";

    import { Audio } from "expo"; // add this

Next, add an initial value for the reference to the background sound. We need it as a class variable so we could stop the sound later once the user logs in:

    constructor(props) {
      super(props);
      this.backgroundSound = null; // add this
    }

Next, add a componentDidMount method with the following code:

    async componentDidMount() {
      try {
        this.backgroundSound = new Audio.Sound();
        await this.backgroundSound.loadAsync(
          require("../assets/sounds/background/opening.mp3")
        ); // load the mp3 file
        await this.backgroundSound.setIsLoopingAsync(true); // make the sound loop after it's done playing
        await this.backgroundSound.playAsync(); // start playing the sound
      } catch (error) {
        console.log("error loading background sound: ", error);
      }
    }

    render () {
      // existing code here...
    }

In the code above, we’re using the async/await pattern to load and play the background sound. To use the async/await pattern, we add the async keyword before the parent function name or the before the function’s open and close parenthesis, if it’s an anonymous function. Inside the function, we can use the await keyword to wait for the promise to resolve before executing the next line of code. This essentially makes the asynchronous function behave as if it were a synchronous one.

The loadAsync method accepts a reference to a file through the require method. This is the same method we’re using to load images in React Native. Most methods in the Expo Audio API are async. This means you either have to use a promise or callback function to get its response. That’s the reason why we need to put the await keyword at the beginning of each method call, so each method will wait for the results of the previous method call before proceeding.

Next, update the login method so it stops the sound once the user logs in. We need to stop the sound because it doesn’t automatically stop once a new sound starts playing. As mentioned earlier, each screen will have its own background sound. That’s why we need to stop it before the sound in the next screen starts playing:

    login = () => {
      let username = this.state.username;

      if (username) {
        this.props.navigation.navigate("TeamSelect", {
          username
        });

        this.backgroundSound.stopAsync(); // add this
      }
    };

Team selection screen background sound

Do the same for the team selection screen. Be sure to load the correct .mp3 file:

    // src/screens/TeamSelectionScreen.js
    import Pusher from "pusher-js/react-native";

    import { Audio } from "expo"; // add this


    constructor(props) {
      // previous code here..

      this.backgroundSound = null; // add this
    }


    async componentDidMount() {
      try {
        this.backgroundSound = new Audio.Sound();
        await this.backgroundSound.loadAsync(
          require("../assets/sounds/background/final-road.mp3")
        );
        await this.backgroundSound.setIsLoopingAsync(true);
        await this.backgroundSound.playAsync();
      } catch (error) {
        console.log("error loading background sound: ", error);
      }
    }

Battle screen background sound

Lastly, do the same for the battle screen:

    // src/screens/BattleScreen.js
    import { Ionicons } from "@expo/vector-icons";

    import { Audio } from "expo"; // add this


    constructor(props) {
      // previous code here..

      this.backgroundSound = null; // add this
    }


    async componentDidMount() {
      // previous code here..

      // add this
      try {
        this.backgroundSound = new Audio.Sound();
        await this.backgroundSound.loadAsync(
          require("../assets/sounds/background/rival.mp3")
        );
        await this.backgroundSound.setIsLoopingAsync(true);
        await this.backgroundSound.playAsync();
      } catch (error) {
        console.log("error loading background sound: ", error);
      }
    }

Pokemon cry sounds

When a user switches to a specific Pokemon on their team or their Pokemon faints, we want to play their cry.

Download their cry (.mp3 file) from the asset folder of the Pokemon Showdown website. Once downloaded, create a cries folder inside src/assets/sounds and copy the files you downloaded over to that folder.

Next, update the src/data/pokemon_data.js file so it includes a cry property for each Pokemon. We need to do this because we can’t really pass a variable to the require function. You can simply copy the contents of the file in the repo if you want. Just be sure the filenames are the same.

Update the PokemonOption component

At this point, we’re now ready to add the cry sounds. Let’s first add the code for playing the cry when the user switches to another Pokemon. Start by importing the Audio package:

    // src/components/PokemonOption/PokemonOption.js
    import { connect } from "react-redux";

    import { Audio } from "expo"; // add this

Next, we need to convert the component into a class-based one:

    class PokemonOption extends Component {
      render() {
        const { pokemon_data, is_selected, action_type } = this.props; // add this

        // add the same return code here..
      }
    }

Note that we’re extracting fewer props in the code above. This is because we’ll be separating the event handler for the onPress event of the TouchableOpacity component.

As mentioned earlier, playing Audio requires the direct parent function to have the async keyword. While you can actually do it like the one below, it’s better if we just refactor the code to declare the function for handling the onPress event separately:

    <TouchableOpacity onPress={async () => {
      // same code here..
    }}>

To refactor the code, copy the existing code inside onPress.

Next, create a selectPokemon function and paste the existing code inside it. Above the existing code, add the props that were previously being extracted:

    render() {
      // same code here..
    }

    // add this
    selectPokemon = async () => {
      // add these:
      const {
        pokemon_data,
        is_selected,
        action_type,
        togglePokemon,
        setPokemon,
        setMessage,
        setMove,
        backToMove,
        opponents_channel
      } = this.props;

      const { id, cry } = pokemon_data; // add this

      // paste existing code here...

    };

Next, update the code you just pasted to play the cry sound when the action_type is switch-pokemon:

    if (action_type == "select-pokemon") {
      // previous code here..
    } else if (action_type == "switch-pokemon") {
      // previous code here..

      // add these:    
      try {
        let crySound = new Audio.Sound();
        await crySound.loadAsync(cry);
        await crySound.playAsync();
      } catch (error) {
        console.log("error loading cry: ", error);
      }

      // same code:
      setTimeout(() => {
        setMessage("Please wait for your turn...");
        setMove("wait-for-turn");
      }, 2000);
    }

Update the MovesList component

Next, we need to update the MovesList component so it plays the cry sound when the opponent Pokemon faints:

    // src/components/MovesList/MovesList.js

    import { connect } from "react-redux";

    import { Audio } from "expo"; // add this

Just like what we did with the PokemonOption component earlier, we also need to refactor this component into a class-based one:

    class MovesList extends Component {
      render() {
        const { moves } = this.props;

        // add existing return code here..
      }
    }

Next, copy the code inside the onPress handler, then update it to use a named function. Pass in the item from the FlatLists’ renderItem method as an argument so we could make use of it inside the selectMove function:

    <TouchableOpacity
      style={styles.container}
      onPress={this.selectMove.bind(this, item)}
    >
      <CustomText styles={styles.label}>{item.title}</CustomText>
    </TouchableOpacity>

Add the selectMove function and paste the code from onPress:

    selectMove = async item => {
      // add these:
      const {
        moves,
        opponent_pokemon,
        setOpponentPokemonHealth,

        backToMove,
        pokemon,
        setMessage,
        setMove,
        removePokemonFromOpponentTeam,
        setOpponentPokemon,
        opponents_channel
      } = this.props;

      // paste existing onPress code here..

    }

Lastly, when the opponent’s Pokemon faints, play the cry sound:

    if (health < 1) {
      // existing code here..

      // add these:
      try {
        let crySound = new Audio.Sound();
        await crySound.loadAsync(opponent_pokemon.cry);
        await crySound.playAsync();
      } catch (error) {
        console.log("error loading cry: ", error);
      }
    }

Update the battle screen

The last thing we need to update is the battle screen. We also need to play the cry sound when the user receives an update that their opponent switched their Pokemon, or when their own Pokemon faints after receiving an attack.

In the code for handling the client-switched-pokemon event, we update the anonymous function so it uses the async keyword. Because we previously had a reference to the pokemon, we can just use it to get the cry:

    // src/screens/BattleScreen.js

    my_channel.bind("client-switched-pokemon", async ({ team_member_id }) => {
      // existing code here..

      // add these:
      try {
        let crySound = new Audio.Sound();
        await crySound.loadAsync(pokemon.cry);
        await crySound.playAsync();
      } catch (error) {
        console.log("error loading cry: ", error);
      }

      // this is existing code:
      setTimeout(() => {
        setMove("select-move");
      }, 1500);
    });

Next, inside the handler for the client-pokemon-attacked event, when the Pokemon faints, play the cry sound:

    if (data.health < 1) { // Pokemon faints
      // existing code here..

      setTimeout(async () => { // note the async
        // existing code here..

        // add these:
        try {
          let crySound = new Audio.Sound();
          await crySound.loadAsync(fainted_pokemon.cry);
          await crySound.playAsync();
        } catch (error) {
          console.log("error loading cry: ", error);
        }
      }, 1000);

      // existing code here..
    }

Note that this time, we’ve placed the async keyword in the function for setTimeout instead of the event handler itself. This is because we only need it on the direct parent function.

Health bar animation

Now it’s time to implement the animations. If you’re new to animations in React Native, I recommend that you check out my article on React Native animations.

Let’s first animate the health bar. Currently, when a Pokemon loses health, their current HP just abruptly changes when they receive the damage. We want to change it gradually so it gives the illusion that the Pokemon is slowly losing its health as it receives the attack:

To accommodate the animations, we first need to convert the HealthBar component to a class-based one. This is because we now need to work with the state:

    // src/components/HealthBar/HealthBar.js

    class HealthBar extends Component {
      render() {
        const { label, currentHealth, totalHealth } = this.props;

        // paste existing return code here..
      }
    }

Next, extract the Animated library from React Native. This allows us to perform animations:

    import { View, Animated } from "react-native"; 

Next, declare the maximum width that the health bar can consume. We’ll be using this later to calculate the width to apply for the current health:

    import CustomText from "../CustomText";

    const available_width = 100; // add this

Next, initialize the state value which will represent the Pokemon’s current health. In the constructor, we also initialize the animated value. This is the value that we’ll interpolate so the health bar will be animated. Here, we’re using the currentHealth passed via props so the health bar animations and health percentage text will always use the current Pokemon’s health:

    class HealthBar extends Component {
      // add these:
      state = {
        currentHealth: this.props.currentHealth // represents the Pokemon's current health
      };

      constructor(props) {
        super(props);
        this.currentHealth = new Animated.Value(this.props.currentHealth); // add this
      }

      // existing code here..

    }

You might be wondering why we need to add a separate state value for storing the Pokemon’s health when we’re already passing it as a prop. The answer is that we also want to animate the number which represents the health percentage while the health bar animation is in progress. The currentHealth values passed via props only represents the current health, so we can’t really update it.

Next, add the getCurrentHealthStyles function. This is where we define how the health bar will be updated while the animation is in progress. As you’ve seen in the demo earlier, the health bar should decrease its width and change its color from colors between green (healthy) to red (almost fainting). That’s exactly what we’re defining here:

    getCurrentHealthStyles = () => {
      var animated_width = this.currentHealth.interpolate({
        inputRange: [0, 250, 500],
        outputRange: [0, available_width / 2, available_width]
      });

      const color_animation = this.currentHealth.interpolate({
        inputRange: [0, 250, 500],
        outputRange: [
          "rgb(199, 45, 50)",
          "rgb(224, 150, 39)",
          "rgb(101, 203, 25)"
        ]
      });

      return {
        width: animated_width,
        height: 8, //height of the health bar
        backgroundColor: color_animation
      };
    };

In the code above, we’re using the interpolate method to specify the input and output ranges of the animation. The inputRange represents the value of the animated value at a given point in time, while the outputRange is the value you want to use when the animated value is interpolated to the corresponding inputRange. Here’s how the values for the animated_width maps out. The number on the left is the inputRange while the one in the right is the outputRange:

  • 0 → 0
  • 250 → 50
  • 500 → 100

The numbers in between the numbers we specified are automatically calculated as the animation in on progress.

The same idea applies to the values for color_animation, only this time, it uses RGB color values as the outputRange.

Next, update the render method so it uses the Animated.View component for the current health and call the getCurrentHealthStyles function to apply the styles. The health percent text should also be updated to make use of the value in the state. It needs to be divided by 5 because the animated value is 5 times the value of the health bar’s available_width:

    render() {
      const { label } = this.props;

      return (
        <View>
          <CustomText styles={styles.label}>{label}</CustomText>
          <View style={styles.container}>
            <View style={styles.rail}>
              <Animated.View style={[this.getCurrentHealthStyles()]} />
            </View>
            <View style={styles.percent}>
              <CustomText styles={styles.percentText}>
                {parseInt(this.state.currentHealth / 5)}%
              </CustomText>
            </View>
          </View>
        </View>
      );
    }

Lastly, add the componentDidUpdate method. This gets invoked immediately after an update to the component occurs. The props don’t necessarily have to have been updated when this occurs, so we need to check whether the relevant prop was actually updated before we perform the animation. If it’s updated, we interpolate the this.currentHealth animated value over a period of 1.5 seconds. The final value will be the new currentHealth passed via props. After that, we add a listener to the animated value. This listener gets executed every time the animated value is updated. When that happens, we update the state value, which represents the Pokemon’s health. This allows us to update the UI with the current health percentage while the animation is in progress:

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.currentHealth !== this.props.currentHealth) { // check if health is updated
        Animated.timing(this.currentHealth, {
          duration: 1500, // 1.5 seconds
          toValue: this.props.currentHealth // final health when the animation finishes
        }).start(); // start the animation

        this.currentHealth.addListener(progress => {
          this.setState({
            currentHealth: progress.value
          });
        });
      }
    }

Pokemon fainting animation

When a Pokemon loses all of its health, we move the PokemonFullSprite component downwards out of the view. This gives the impression that the Pokemon collapsed. Here’s what it looks like (minus the boxing gloves, we’ll add that later):

Just like what we did with all the previous components, we also need to convert this one to a class-based one.

Once you’ve converted the component to a class-based one, import the Animated library:

    // src/components/PokemonFullSprite/PokemonFullSprite.js

    import { Image, Animated } from "react-native";

Next, add the animated value that we’re going to interpolate:

    constructor(props) {
      super(props);
      this.sprite_translateY = new Animated.Value(0);
    }

Next, update the render method to specify how the vertical position of the component will change. In this case, an inputRange of 0 means that it’s in its original position. Once it becomes 1000, it’s no longer visible because its initial vertical position has moved 1000 pixels downwards. To apply the styles, specify it as an object under transform. This allows us to perform translation animations similar to the ones used in CSS3:

    render() {
      const { spriteFront, spriteBack, orientation } = this.props;
      let sprite = orientation == "front" ? spriteFront : spriteBack;

      // add these:
      const pokemon_moveY = this.sprite_translateY.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1000]
      });

      // use Animated.Image instead of Image, and add transform styles
      return (
        <Animated.Image
          source={sprite}
          resizeMode={"contain"}
          style={[
            styles.image,
            {
              transform: [
                {
                  translateY: pokemon_moveY
                }
              ]
            }
          ]}
        />
      );
    }

When the component is updated, we only start the animation if the Pokemon has fainted. If it’s not then we set the initial value. This way, the component doesn’t stay hidden if the user switched to a different Pokemon:

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.isAlive !== this.props.isAlive && !this.props.isAlive) { // if Pokemon has fainted
        Animated.timing(this.sprite_translateY, {
          duration: 900,
          toValue: 1
        }).start();
      } else if (prevProps.isAlive !== this.props.isAlive && this.props.isAlive) { // if Pokemon is alive
        this.sprite_translateY.setValue(0); // unhides the component
      }
    }

The last step is to add the isAlive prop when using the PokemonFullSprite component in the battle screen:

    // src/screens/BattleScreen.js
    <PokemonFullSprite
      ...
      isAlive={opponent_pokemon.current_hp > 0}
    />


    <PokemonFullSprite
      ...
      isAlive={pokemon.current_hp > 0}
    />

Pokemon switch animation

When the user switches Pokemon, we’re going to make a Pokeball bounce and scale the Pokemon gif up. This gives the impression that the user has thrown it and the Pokemon came out of it:

To implement this animation, we also need to update the PokemonFullSprite component. Start by importing the additional components and libraries we need from React Native. This includes the View component and the Easing library to implement easing animations:

    // src/components/PokemonFullSprite/PokemonFullSprite.js
    import { View, Image, Animated, Easing } from "react-native";

Next, update the constructor to include three new animated values. As mentioned earlier, we’re going to render a Pokeball which we will bounce so we need to translate its Y position. Aside from that, we also need to hide it so we have pokeball_opacity. Once the Pokeball is hidden, we want to scale up the Pokemon gif:

    constructor(props) {
      // previously added code..

      // add these
      this.pokeball_y_translate = new Animated.Value(0); // for updating the Y position of the Pokeball
      this.pokeball_opacity = new Animated.Value(0); // for animating the Pokeball opacity
      this.sprite_scale = new Animated.Value(0); // for scaling the Pokemon gif
    }

Next, update the render method so it specifies how we’re going to interpolate the animated values we declared in the constructor:

    const pokemon_moveY = ... // same code

    // add these:
    const pokemon_scale = this.sprite_scale.interpolate({
      inputRange: [0, 0.5, 1],
      outputRange: [0, 0.5, 1] // invisible (because zero size), half its original size, same as original size
    });

    const pokeball_moveY = this.pokeball_y_translate.interpolate({
      inputRange: [0, 1, 2],
      outputRange: [0, 50, 25] // top to bottom Y position translate
    });

    const pokeball_opacity = this.pokeball_opacity.interpolate({
      inputRange: [0, 0.5, 1],
      outputRange: [1, 0.5, 0] // full opacity, half opacity, invisible
    });

Next, add an animated image on top of the Pokemon gif, then add the interpolated values to both the Pokeball image and the Pokemon gif. Since React Native doesn’t allow us to return siblings, we wrap everything in a View component:

    return (
        <View>
          <Animated.Image
            source={require("../../assets/images/things/pokeball.png")}
            style={{
              transform: [
                {
                  translateY: pokeball_moveY
                }
              ],
              opacity: pokeball_opacity
            }}
          />

          <Animated.Image
            source={sprite}
            resizeMode={"contain"}
            style={[
              styles.image,
              {
                transform: [
                  {
                    translateY: pokemon_moveY
                  },
                  {
                    scale: pokemon_scale
                  }
                ]
              }
            ]}
          />

        </View>
      );
    }

You can get the Pokeball image from this website. Select the 32px .png file. That’s also the source of the image included in the repo. Create a things folder inside the src/assets/images directory, move the file in there, and rename it to pokeball.png.

Because we need to animate in two instances: componentDidMount and componentDidUpdate, we create a new function that will start the animations for us:

    animateSwitchPokemon = () => {
      // initialize the animated values
      this.sprite_translateY.setValue(0);
      this.pokeball_opacity.setValue(0);
      this.pokeball_y_translate.setValue(0);
      this.sprite_scale.setValue(0);

      // perform the animations in order
      Animated.sequence([
        // bounce the Pokeball
        Animated.timing(this.pokeball_y_translate, {
          toValue: 1,
          easing: Easing.bounce,
          duration: 1000
        }),

        // hide the Pokeball
        Animated.timing(this.pokeball_opacity, {
          toValue: 1,
          duration: 200,
          easing: Easing.linear
        }),

        // scale the Pokemon gif up so it becomes visible
        Animated.timing(this.sprite_scale, {
          toValue: 1,
          duration: 500
        })
      ]).start();
    };

In the code above, we first re-initialize the animated values. This is because this component doesn’t really get unmounted when a Pokemon faints and re-mounted again once the user switches to another Pokemon. If we don’t do this, the subsequent Pokemon’s that we switch to after the first one has fainted will no longer be visible. That is because the component will already have been in its final state of animation.

Once we’ve re-initialized the animated values, we performed the animations in order:

  1. Bounce the Pokeball.
  2. Hide the Pokeball.
  3. Scale the Pokemon gif up.

When the component is mounted for the first time, we execute the function for animating it:

    componentDidMount() {
      this.animateSwitchPokemon();
    }

Also, do the same when the component is updated. The only time we want to perform the animations for switching a Pokemon is when the user switches to a new one. Since we’re already passing the Pokemon name as a props, we simply check if the current one is not the same as the previous:

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.isAlive !== this.props.isAlive && !this.props.isAlive) {
        // previous code here..
      } else if (prevProps.pokemon !== this.props.pokemon && this.props.isAlive) {
        this.animateSwitchPokemon();
      }
    }

Pokemon move animation

Next, we’re going to implement the Pokemon move animations. We’ll only implement a single generic move animation because it would take us forever if we’re going to implement everything via code. Here’s what the animation looks like:

Just like all the previous Pokemon-related animations, we’ll also be using the PokemonFullSprite component for this. Start by adding the new animated values that were going to interpolate. This includes the following:

  • pokemon_opacity - to seemingly make the Pokemon disappear for a split second to indicate that it received damage.
  • punch_opacity - for making the boxing gloves image appear while an attack is made, and disappear once it reaches its final destination (right above the Pokemon’s head).
  • punch_translateY - for moving the boxing gloves vertically across the target Pokemon when it’s attacked.

Here’s the code. Add these after the last animated value in the constructor:

    // src/components/PokemonFullSprite/PokemonFullSprite.js
    this.pokemon_opacity = new Animated.Value(0);
    this.punch_opacity = new Animated.Value(0);
    this.punch_translateY = new Animated.Value(0);

Next, we specify how the new animated values will be interpolated. This is inside the render method:

    const pokeball_opacity = ... // same code

    // add these:
    const punch_opacity = this.punch_opacity.interpolate({
      inputRange: [0, 1],
      outputRange: [0, 1]
    });

    const punch_moveY = this.punch_translateY.interpolate({
      inputRange: [0, 1],
      outputRange: [0, -130] // negative value because we're moving upwards
    });

    const pokemon_opacity = this.pokemon_opacity.interpolate({
      inputRange: [0, 0.5, 1],
      outputRange: [1, 0.2, 1] // appear, disappear, appear
    });

Next, update the target components. The first one is the Pokemon gif. Add the opacity style:

    <Animated.Image
      source={sprite}
      resizeMode={"contain"}
      style={[
        styles.image,
        {
          transform: [
            {
              translateY: pokemon_moveY
            },
            {
              scale: pokemon_scale
            }
          ],
          opacity: pokemon_opacity // add this
        }
      ]}
    />

The second one hasn’t been added yet. Add it right below the Pokemon gif. This includes both transform and opacity animations:

    <Animated.Image
      source={require("../../assets/images/things/fist.png")}
      style={[
        styles.punch,
        {
          transform: [
            {
              translateY: punch_moveY // for moving it vertically across the Pokemon gif
            }
          ],
          opacity: punch_opacity // for making it appear and disappear
        }
      ]}
    />

You’ll need to download the image asset we’re using above. Select the 32px .png file. That’s also the source of the image in the GitHub repo. Move the file inside the src/assets/images/things folder and rename it to fist.png.

Next, add the styles. The component should be absolutely positioned so that it can overlap with the Pokemon gif:

    const styles = {
      // previously added code here..  

      // add these:
       punch: {
        position: "absolute", // very important
        bottom: -40,
        left: 50
      }
    };

Next, add the function for starting the move animations:

    animateDamagePokemon = () => {
      // reset the animated values
      this.punch_opacity.setValue(0);
      this.punch_translateY.setValue(0);
      this.pokemon_opacity.setValue(0);

      Animated.sequence([
        // make the boxing gloves visible
        Animated.timing(this.punch_opacity, {
          toValue: 1,
          duration: 10,
          easing: Easing.in
        }),

        // move the boxing gloves upwards across the Pokemon
        Animated.timing(this.punch_translateY, {
          toValue: 1,
          duration: 300,
          easing: Easing.in
        }),

        // hide the boxing gloves
        Animated.timing(this.punch_opacity, {
          toValue: 0,
          duration: 200,
          easing: Easing.in
        }),

        // momentarily hide the Pokemon (to indicate damage)
        Animated.timing(this.pokemon_opacity, {
          toValue: 1,
          duration: 850,
          easing: Easing.in
        })
      ]).start();
    };

Next, we call the animateDamagePokemon function when the current health changes. This may also happen when the user switches Pokemon so we need to make sure that the animation doesn’t execute if the previous Pokemon isn’t the same as the one the user switched to:

    componentDidUpdate(prevProps, prevState) {
      // add these:
      if (
        prevProps.pokemon === this.props.pokemon &&
        prevProps.currentHealth !== this.props.currentHealth
      ) {
        this.animateDamagePokemon();
      }

      // existing code here..
    }

Next, when we use the PokemonFullSprite component inside the battle screen, we need to add the new currentHealth prop. When its value changes, that’s the queue for the component to render the move animation:

    // src/screens/BattleScreen.js
    <PokemonFullSprite
      ...
      currentHealth={opponent_pokemon.current_hp}
    />

    <PokemonFullSprite
      ...
      currentHealth={pokemon.current_hp}
    />

Lastly, we need to move the code for dispatching the action for updating the Pokemon’s health to the very first line when the callback function is called. This is because setting the Pokemon’s health triggers the move animation as well, and we want to perform it while the health is being animated:

    // src/screens/BattleScreen.js
    my_channel.bind("client-pokemon-attacked", data => {
      setPokemonHealth(data.team_member_id, data.health); // move this (previously above: setMove("select-move"))

      // previously added code here..
    });

Conclusion

We’ve reached the end of this tutorial. Even though it took us three tutorials to implement it, there are still lots of things that need to be covered:

  • Only a handful of Pokemon can be selected, and their moves are limited.
  • There are two-turn moves like Fly, Dig, and Solar Beam in the moves_data.js file, but they’re not really implemented as such.
  • Moves that are supposed to modify base stats aren’t also implemented. There are also no status conditions such as frozen, burned, or paralyzed.
  • Players can’t use or equip items such as the max potion, berries to their Pokemon.

You might also have noticed that there’s a bug in the app. I call it “Zombie mode”. When your Pokemon faints, you can actually go to the Pokemon move selection screen and attack with your fainted Pokemon.

Lastly, there’s no functionality yet to inform both players that someone has won. Even though it’s obvious, it’s always good to acknowledge it. So if you’re interested, I encourage you to develop the app further.

In this tutorial, you learned how to play background sounds within an app using Expo’s Audio API. You also learned how to implement animations in React Native.

That also wraps up the series. In this series, you learned how to re-create the battles in the classic Pokemon game using React Native and Pusher. Along the way, you learned how to use Redux, Pusher Channels, audio, and animations in React Native.

You can find the code for this app on its GitHub repo. The code added to this specific part of the series is on the animations-and-sounds branch.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.