Parrot

The main character will be represented by this component, which will comprise of two different images (the same parrot with its wings up and down) driven by the Y position property passed by <GameContainer />:

/*** src/components/parrot.js ***/

import React from “react";
import { Image } from “react-native";
import { W, H } from “../constants";

export default class Parrot extends React.Component {
  constructor() {
    super();
    this.state = { wings: “down" };
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.props.y < nextProps.y) {
      this.setState({ wings: “up" });
    } else if (this.props.y > nextProps.y) {
      this.setState({ wings: “down" });
    }
  }

  render() {
    let parrotImage;
    if (this.state.wings === “up") {
      parrotImage = require(“../../images/parrot1.png");
    } else {
      parrotImage = require(“../../images/parrot2.png");
    }
    return (
      <Image
        source={parrotImage}
        style={{
          position: “absolute",
          resizeMode: “contain",
          left: this.props.x,
          top: this.props.y,
          width: 12 * W,
          height: 12 * W
        }}
      />
    );
  }
}

We use a state variable named wings to pick which image the parrot will be--when it is flying up the image with the wings down will be displayed while the wings up will be shown when flying down. The way this will be calculated is based on the position of the bird on the y axis passed as a property from the container:

  • If the Y position is lower than the previous Y position means the bird is going down and therefore the wings should be up
  • If the Y position is higher than the previous Y position means the bird is going up and therefore the wings should be down

The size of the parrot is fixed to 12 * W both for the height and width as the sprite is a square and we want it to be sized relative to the width of each screen device.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.129