Compose Multiple 3D Objects into one Component in React VR

One of React's core concepts is component composition. React VR is no different in that regard. You can take an existing component and wrap it into a new React component.

We'll do so by creating a <Tree/> component out of simple shapes, a <Cylinder/> trunk and a <Sphere/> tree crown. When making our <Tree/> we'll also see how the position of shapes is relative to the <View/> and learn how we can leverage this superpower!

Code

You must be a Member to view code

Transcript

00:00 First, we create a function named tree. The function component receives props and renders a wrapping view. Inside, we add a sphere to represent the tree crown, and therefore color it green. In addition, we move it two meters away from us.

00:18 Then we add our work in progress tree to our scene. Right now, the tree is positioned two meters away from us because it's hard-coded in a sphere element inside the tree component. In a previous lesson, you learned that all 3D primitives by default are located at zero on all axis.

00:39 While not mandatory, I recommend you to follow this pattern, and rather move the tree than moving its rendered elements. Therefore, we provide a style property to our tree, translating it three meters away.

00:54 To make this work, in our tree component we make sure the property style is applied to the wrapping view. We can reduce the inner Z translation of the sphere to zero. Next up, we add a cylinder representing the tree trunk. Therefore, we color it brown and modify the radius.

01:18 Both parts are shown in our scene, but yet our tree component doesn't really resemble a tree, since both parts are rendered at the zero position of all axis. To fix that, we move the crown a bit further up by changing the sphere's translate Y to 08 meters.

01:35 There is one important thing happening here that I want to highlight. The translation of the sphere is not absolute, but rather relative to the view. This is a powerful tool, since you position parts of a more complex component relative to the component's origin using such a wrapping view.

01:55 Let me demonstrate you this superpower by adding a second tree, which we just move 1.1 meters next to the first one.