What is Three Js?

Three.js is an open-source JavaScript library used to display graphics, 3D and 2D objects on web browsers. The Three.js application programming interface is used to create and display animated 3D computer graphics in a web browser using WebGL.

React Native has proven to be a popular, effective, and efficient way to create a mobile app. It can also be used to develop games such as Candy Crush. But what if you want to make more advanced games? With Expo-3, you can use Three.js WebGL lib in React Native easily to develop 3D games. In this blog post, we will go over how to set up Expo-3 and create our first 3D game using React Native and the Expo-3 Gsap animation library.

If you want to develop  your app, you can create a project using crna command to use the three.js template:  

npx create-react-native-app -t with-three

In an existing app, you can now add three.js with yarn:

yarn add three expo-three expo-gl

Let's  writing start Code:

We needed to import, three.js components to add our renderer later;

import {

  AmbientLight,

  SphereGeometry,

  Fog,

  GridHelper,

  Mesh,

  MeshStandardMaterial,

  PerspectiveCamera,

  PointLight,

  Scene,

  SpotLight,

} from "three";

After importing the main component, now you can use GLView inside the main View in your app. In addition, you need to add flex style (to fill all screens) and add an onContextCreate function with gl parameter.


  style={{ flex: 1 }}

  onContextCreate={async (gl) => {}}

/>

The onContextCreate function is responsible to receive a GL parameter and use it to create a scene, for instance, it adds other things like light, objects, camera, floor, and a lot more.

To make the app faster and simple, we need an instance, and we will list it for you to understand easily, and after, show the code example.

1. Renderer: In context creation, we will instance a Renderer and give it a gl parameter and background color to make our scene later.

2. Scene: The scene is where our game will take place, and where we will add the other objects that make it up.

3. Camera: The camera will be the user's vision of our scene.

4. Lights (AmbientLight and PointLight): The lights will illuminate our scene and objects and make shadows possible.

5. Mesh(Sphere or Cube): Meshes are objects you can add to your scene, you can edit your format, or import from other platforms, in this case, we will use a simple sphere mesh.

Before start writing the onContextCreate function, we need to create a class with our Sphere Mesh (mentioned object).


class SphereMesh extends Mesh {

  constructor() {

    super(

      new SphereGeometry(0, 50, 20, 0, Math.PI * 2, 0, Math.PI * 2),

      new MeshStandardMaterial({

        color: 0xff0000,

      })

    );

  }

}


Now, we need to instance Sphere and Camera, and these steps can be coded in whatever you want (like state, context, redux…), but in this case, I will instance in App.js main class. Also, we will declare 3 variables with the camera's initial position, this variable represents the distance between our sphere and our camera, don’t worry, you will understand usage soon.


const sphere = new SphereMesh();

const camera = new PerspectiveCamera(100, 0.4, 0.01, 1000);


let cameraInitialPositionX = 0;

let cameraInitialPositionY = 2;

let cameraInitialPositionZ = 5;

Currently, we needed to add all code on onContextCreate, and your GLView will look like this:


  style={{ flex: 1 }}

  onContextCreate={async (gl) => {

    // GL Parameter disruption

    const { drawingBufferWidth: width, drawingBufferHeight: height } = gl;


    // Renderer declaration and set properties

    const renderer = new Renderer({ gl });

    renderer.setSize(width, height);

    renderer.setClearColor("#fff");


 // Scene declaration, add a grid helper and fog to see axes' dimensions

    const scene = new Scene();

    scene.fog = new Fog("#3A96C4", 1, 10000);

    scene.add(new GridHelper(10, 10));


    // Add all necessary lights

    const ambientLight = new AmbientLight(0x101010);

    scene.add(ambientLight);


    const pointLight = new PointLight(0xffffff, 2, 1000, 1);

    pointLight.position.set(0, 200, 200);

    scene.add(pointLight);


    const spotLight = new SpotLight(0xffffff, 0.5);

    spotLight.position.set(0, 500, 100);

    spotLight.lookAt(scene.position);

    scene.add(spotLight);


    // Add sphere object instance to our scene

    scene.add(sphere);


    // Look to the sphere and set the camera position

    camera.position.set(

      cameraInitialPositionX,

      cameraInitialPositionY,

      cameraInitialPositionZ

    );


    camera.lookAt(sphere.position);


    // Render function

    const render = () => {

      requestAnimationFrame(render);

      renderer.render(scene, camera);

      gl.endFrameEXP();

    };

    render();

  }}

/>

At this point, we already have a scene with our object instance and lights.  To complete the app, now we’ll make the sphere move to the front and back on click.

To make animations at 60 fps, we need to use Gsap. This library is used by many developers and it's easy to use. First, we'll install Gsap with yarn.


yarn add gsap


With gsap installed, import the TweenMax method from the library.


import { TweenMax } from 'gsap';


Now we will make a function, changing our camera position and sphere, using the Tween method to animate it. This function will receive a number parameter that will be the distance for the sphere that will move about the Z axe.


The most important part of our creation is to add some buttons on our screen. We'll use TouchableWithoutFeedback components and add some styles. Using TouchableWithoutFeedback and adding some style, we can create our two buttons that will move the Z axe to the front and back respectively. Please note that this component can be attached as a child of GLView.


 

 

    onPressIn={() => move(-0.2)}

  >

   

      fontSize: 36, 

      MozUserSelect: "none",

      WebkitUserSelect: "none",

      msUserSelect: "none"

    }}>

      UP

        

 

 

    onPressIn={() => move(0.2)}

  >

   

      fontSize: 36, 

      MozUserSelect: "none",

      WebkitUserSelect: "none",

      msUserSelect: "none"

    }}>

      DOWN

   

 

What is the Importance of Three JS  for Web & App Development?

Three.JS uses WebGL which is a JavaScript API used to render interactive 3D and 2D graphics in web browsers without using any plugins. Using WebGL, Three.js enables your browser to render smooth 3D animations, and being cross-browser it takes great advantage of multidimensional objects on the web.

Hiring the right Three.js developer for your project can be a serious task. But with DigiPrima, you can hire the right developer to bring your project to life. 

What is the purpose of three JS?

Three. js is a JavaScript-based WebGL engine that can run GPU-powered games and other graphics-driven apps directly from the browser. Three js libraries provide many features and APIs for creating 3D scenes in your browser.

Want to build a Virtual Reality Web App with Blender and Three.js? Hire Our best Three.js Developers

Web, Mobile & Software Development Services by DigiPrima

Software Consulting Services

Looking for IT consulting services? Great your search end here, because we are top rated Software, Web and Mobile App development company.

We have already successfully completed ~1000 projects. Take advantage of our all-round software application development services.

KNOW MORE ABOUT US
READ MORE RELATED BLOGS