July 15, 2021
Building a VR app with React 360

As a tech head, you’re probably aware of virtual reality and its various applications. Video games, web and mobile apps, and more can reap the benefits of VR’s amazing features.

If your next development goal is creating VR apps and you’re familiar with the React ecosystem, you’re in luck. You can now develop amazing VR experiences using React 360 and JavaScript.

In this tutorial, we’ll show you how to develop a simple and interactive React virtual reality application using React 360. By the end, you should be ready to build your first VR app in React.

We’ll cover the following:

What is React 360?
Installing React 360
Adding background assets
VR interactions
Adding immersive sounds
Running your React VR application

What is React 360?

React 360 is a library that utilizes a lot of React Native functionality to create virtual reality apps that run in your web browser. It uses Three.js for rendering and comes as an npm package. By combining modern APIs such as WebGL and WebVR with the declarative power of React, React 360 helps simplify the process of creating cross-platform VR experiences.

Learning how to use React 360 is a great way to kickstart your VR development career. In this tutorial, we’ll cover all the basics to help you get started using React 360.

Installing React 360

First and foremost, you need to install the React 360 CLI. This will give you access to all the necessary commands to assist you in developing a virtual reality application.

Now, go to the desired folder through the command terminal and run the following command:

npm install -g react-360-cli

This is a one-time install, so you don’t have to do this every time. The benefit of being in the project folder is that it makes the following step easier.

After installation, create a new project called my-project (creative, right?) and type:

react-360 init my-project

You have successfully created your first virtual reality application with React 360.

To view the app in your browser, navigate to the my-project folder via the terminal and then run npm start. This will guide you to the destination in the browser. Alternatively, you can access the output by following http://localhost:8081/index.html.

Here’s what the app should look like:

React 360 Template Screen

Now that you have the app up and running, let’s talk about the code in detail. Two important files we’ll be working with are client.js and index.js. The index.js file consists of four parts:

Class
Imports
Styles
Component Registry

We’re importing React to use its class functionality. We’ll gather some parts from React 360 to build a VR environment:

import React from ‘react’;

import {
AppRegistry,
StyleSheet,
Text,
View,
} from ‘react-360’;

export default class my_project extends React.Component {
render() {
return (

Welcome to React 360

);
}
};

const styles = StyleSheet.create({
panel: {
width: 1000,
height: 600,
backgroundColor: ‘rgba(255, 255, 255, 0.4)’,
justifyContent: ‘center’,
alignItems: ‘center’,
},
greetingBox: {
padding: 20,
backgroundColor: ‘#000000’,
borderColor: ‘#639dda’,
borderWidth: 2,
},
greeting: {
fontSize: 30,
},
});

AppRegistry.registerComponent(‘my_project’, () => my_project);

The class syntax and components are quite similar to React and React Native, respectively. The View component allows you to render various aspects of the VR world and, if you want, to play with the look and feel. The Style attribute and StyleSheet will help you do that. There are numerous resemblances to React Native and CSS functionality here.

When it comes to the Text component, you can create dynamic text to display all kinds of data for the user. In the end, the class needs to be registered to the client for rendering.

You’ll notice that the init function in the client.js file makes a new instance for your project and then utilizes the class from the index.js file to assign a render method to this project. After that, the project environment is applied to a panoramic image, followed by the execution of the init function.

import {ReactInstance} from ‘react-360-web’;

function init(bundle, parent, options = {}) {
const r360 = new ReactInstance(bundle, parent, {
fullScreen: true,
…options,
});

r360.renderToSurface(
r360.createRoot(‘my_project’, { }),
r360.getDefaultSurface()
);

r360.compositor.setBackground(r360.getAssetURL(‘simmes-start-screen.jpg’));
}

window.React360 = {init};

Those are the basics of React 360 functionality, and you’re good to go with your first VR app development. Now that you know how a React VR app is made, let’s go through some steps to customize it.

Adding background assets

You can apply any panoramic image to the VR background using React 360. For this tutorial, we’re using a Simmes free image; you can use any image you like.

To use a panoramic image for the background, add the desired image to the static_assets folder. This folder contains all the static assets, such as pictures, music, and models, and React 360 searches for them here.

Use the command below to update the background:

r360.compositor.setBackground(r360.getAssetURL(‘simmes-start-screen.jpg’));

VR interactions

One of the most important and engaging aspects of any application is interaction. Without interaction, an app is lifeless. You can add this vital functionality to your React VR app by adding the VrButton component to the index.js files’ imports as follows:

import {
AppRegistry,
StyleSheet,
Text,
View,
VrButton
} from ‘react-360’;

Next, add a counter to record the number of clicks. Start by setting the click count to zero:

state = {
  count: 0
};

The next step is to write an increment function:

_incrementCount = () => {
  this.setState({
    count: this.state.count + 1
 })
}

In the end, we’ll render the VrButton like so:

<View style={styles.panel}>
        <VrButton
          onClick={this._incrementCount}
          style={styles.greetingBox}>
          <Text style={styles.greeting}>
            {`You have visited Simmes ${this.state.count} times`}
         </Text>
       </VrButton>
</View>

You’ve successfully set up the button and you can now see the number of people who visit your VR world.

Adding immersive sounds

Not all apps you create will require sound. However, when it comes to games, videos, and other immersive experiences, sounds are essential.

To add sound to our VR app, we need to fetch a few more things from React 360.

import {
  asset,
 AppRegistry,
 NativeModules,
 StyleSheet,
 Text,
 View,
 VrButton
} from ‘react-360’;

The next step is to import the AudioModule from NativeModules and set a new const:

const { AudioModule } = NativeModules;

Once the new const is set, we can add specific functionality to the way the sound plays. For example, we can make it start playing upon the click of the button and stop when the button is clicked again.

To make this work, we’ll add a Boolean value to the state:

state = {
  count: 0,
  playSound: false
};

Finally, we’ll write another function to manage the way sound plays:

_playSound = () => {
    this.setState({
      playSound: !this.state.playSound
   });

    if (this.state.playSound) {
      AudioModule.createAudio(‘sza’, {
        source: asset(‘brokenclocks.mp3’),
        volume: 0.5
     });

      AudioModule.play(‘sza’);
   }
    else {
      AudioModule.stop(‘sza’);
   }
  }

Once executed, this function upgrades the playSound state, which is set to false. The way the sound plays will depend on the value assigned to playSound. To make it play, an audio instance has to be created via the createAudio component.

Once created, you can play the audio via the assigned name. This only occurs when playSound is set to true. The sound stops playing when it is false. That’s why we make a new instance every time playSound is true.

We’ll now create a button to start and stop playing the sound. Here’s what the code will look like:

<View style={styles.panel}>
<VrButton
    onClick={this._incrementCount}
    style={styles.greetingBox}>
    <Text style={styles.greeting}>
     {`You have visited Simmes ${this.state.count} times`}
  </Text>
 </VrButton>
 <VrButton
   onClick={this._playSound}
   style={styles.greetingBox}>
   <Text style={styles.greeting}>
     {‘You can play the music of your people’}
   </Text>
  </VrButton>
</View>

Your VR app is now complete! Let’s run the application to see how it looks.

Running your React VR application

You can view the app via the run npm start command. Your first React VR app, called “My Project,” should contain the background that you chose and two buttons. One button controls the audio and the other keeps track of the number of users who visit the application.

You can now invite your friends and family to play with your new VR app and brainstorm new ideas for the app with fellow programmers. The possibilities are endless.

I hope this tutorial helped you understand React 360 a little better.

Tell us about your experience with React 360. What do you think is the best way to create VR apps? We would love to hear from you.

The post Building a VR app with React 360 appeared first on LogRocket Blog.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send