# Adding a UI into the world

> Learn how to create an in-world UI on a 3D model in Unreal Engine, with retro effects for an authentic 70s-80s appearance.

> Documentation index: https://coherent-labs.com/llms.txt lists every page of this documentation as Markdown; the full text is in https://coherent-labs.com/llms-full.txt.

Source: https://coherent-labs.com/blog/uitutorials/tetris-ui-in-world/

## Adding a UI into the world

ui tutorials

11/8/2024

Martin Bozhilov

1. Overview
2. Resources
3. Getting started - Unreal Engine
   1. Setting up the scene
   2. Adding in-world UI
   3. Adjusting the plane to fit the screen
   4. Making the TV emit light
4. Getting started - Frontend
   1. Making TV on/off animations
   2. Adding the old tv screen noise effect
   3. Implementing a pause menu to turn off the TV

Integrating an interactive UI directly into the game world creates a more immersive experience, allowing players to engage with the interface as a natural part of the environment.

## Overview

In this tutorial, we’ll guide you through adding an existing UI to the game world and seamlessly blending it with the environment using Gameface’s `in-world UI` feature in Unreal Engine. We’ll enhance our `Tetris UI` sample by adding effects and animations, helping to integrate it naturally into the scene for a more authentic, immersive look.

## Resources

The Assets for this tutorial have been taken from [Sketchfab ](https://sketchfab.com/feed)and [fab ](https://www.fab.com/).

List of assets:

- [1970’s Vintage TV](https://www.fab.com/listings/e9748b75-8246-46c5-bf2b-ac6c100b8957)
- [NES Controller](https://sketchfab.com/search?q=nes+controller\&type=models)
- [Nintendo NES](https://sketchfab.com/3d-models/nintendo-nes-original-6de5054340184509af6f301c7f3fac57)
- [Carpet](https://sketchfab.com/3d-models/kuuma-ye-rug-by-kristiina-lassus-5f5de1ba643746fc9da76d2cac94fbb3)

## Getting started - Unreal Engine

We’ll begin by setting up the project in Unreal Engine. Use the [getting started guide ](https://docs.coherent-labs.com/unreal-gameface/integration/gettingstarted/)from our documentation to install the Gameface plugin and integrate it into an existing project or use the sample project created by the installer.

Once that’s complete, create a new blank map in Unreal Engine to start configuring your setup.

### Setting up the scene

We’ll start by importing our assets into a newly created level and setting up a simple scene of a dark room with a console and a TV for demonstration purposes.

### Adding in-world UI

Next, we’ll add the in-world UI. To do this, go to the Gameface plugin’s dropdown menu and select the `Add in-world UI` option. This will add a `CohtmlPlane` actor to your world, containing a plane mesh with the `cohtmlMaterial` applied to display the UI. The `cohtmlMaterial` is used as the material for the plane mesh, rendering the UI onto it. To learn more about Gameface’s `in-world UI` feature, you can reference [our documentation ](https://docs.coherent-labs.com/unreal-gameface/integration/gettingstarted/#4-add-in-world-ui).

To display your UI, go to the plane’s details panel. In the properties of the Cohtml Gameface Component, locate the URL field and specify the path to the HTML page you want to display in your world.

**Important:** Ensure your HTML page is included in your game’s `uiresources` folder otherwise, the page will not render.

And thats it! Now, if you hit play, your HTML page will be displayed on the plane.

### Adjusting the plane to fit the screen

To make the plane blend naturally with the TV and achieve the classic curved appearance of old CRT screens, we’ll use Unreal Engine’s **Modeling Tool** to slightly bend the plane. Alternatively, you can model a curved plane in a 3D software like `Blender`, import it into Unreal, and replace the plane in the `CohtmlPlane` actor.

#### Bending the plane

**Click here for more information on how we did our plane modeling.**

First, resize and overlay your plane on top of the TV screen to better gauge how much to bend the plane.

Next up, open the modeling tool and select **Deform**, and set the resolution to 10 on all axes.

Now, start bending the plane. The simplest method is to select the outer rows and columns one by one and adjust their position on the Y-axis, as shown below:

*Here, we lowered the Y-axis values of the outer points of the mesh by 2 to bend it backward*

Apply the same method to the remaining sections until you achieve the desired curvature.

A useful tip is to toggle the visibility of the TV object to check how the plane aligns with it and identify areas needing further adjustments. In the image below, the plane is almost finished, but the center needs to be bent slightly more forward.

Here’s the finished result:

### Making the TV emit light

To give the TV a more realistic glow, we’ll create a simple actor with a Point Light component as its child. Place the light slightly in front of the plane and adjust its position until it looks natural.

Feel free to experiment with the light settings and adjust the color to match your UI. In our example, we used the color `#00F1ACFF`.

To add dynamic behavior, we’ll attach some logic to the light, which will later sync with a `CSS` effect to make the TV appear to turn on and off procedurally.

#### Setting up light logic

1. Set the initial intensity of the Point Light to 0.
2. Open the blueprint editor for the light actor and create a custom event called `SetLightIntensity`. This event will accept one argument—a float value to set the light’s intensity.

The logic for this event is straightforward. We’ll increase the light’s intensity in two stages, with brief delays in between

And then simply connect the logic to `Event BeginPlay` to trigger it when the level starts.

#### Setting up TV turn off logic

To make the TV turn off, we’ll reuse the `SetLightIntensity` event we created earlier by calling it from the UI with an argument of 0 for the light intensity.

Open the blueprint for the `CohtmlPlane` actor. In the `Event BeginPlay` node, register the `Cohtml Component` for a JavaScript event. For more details on how to trigger events from the UI, refer to [our documentation ](https://docs.coherent-labs.com/unreal-gameface/integration/ui-scripting/jsinteractions/#ui-scripting-with-c),

Then you need to specify the custom event which will trigger from the UI. In this case, we’ll call it `QuitGame`. The event will simply get the light actor and call the `SetLightIntensity` event but with intensity of 0, effectively turning off the light.

And with that, we’ve completed the Unreal Engine setup! Next, we’ll move on to setting up the frontend to bring the UI to life.

## Getting started - Frontend

For the UI of this tutorial, we will be enhacing one of our existing samples - the **Tetris UI**, which you can find in the `${Gameface package}/Samples/uiresources/TetrisInventoryUI` directory. Or if you have installed our Unreal `Coherent Sample` project you can find it in the `Content/uiresources/TetrisInventoryUI` directory.

Because it is an existing project, everything is already setup for us, now let’s just modify it.

### Making TV on/off animations

To create the effect of the TV turning on and off, we’ll modify the HTML by adding a wrapper element around the content and applying animations to it. These animations will control the `width`, `height`, and `opacity` of the container holding the content, simulating the TV’s behavior.

Start by wrapping the entire content inside the `<body>` tag with a` <div>` element that has the class `content-container`

```html
<body>
    <div class="content-container">
        <!-- Rest of the HTML here -->
    </div>
</body>
```

Next, slightly modify the `body` styles and define the styles for the `content-container` and its animations:

```css
body {
    background-color: rgb(19, 19, 19);
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.content-container{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    animation: tvOn 1s forwards;
}

.content-container.screen-off{
    animation: tvOff 1s forwards;
}

@keyframes tvOn {
    0% {
        width: 0%;
        height: 1%;
        opacity: 0;
    }

    75% {
        width: 100%;
        height: 2%;
    }

    100% {
        width: 100%;
        height: 100%;
        opacity: 1;
    }
}

@keyframes tvOff {
    0% {
        width: 100%;
        height: 100%;
        opacity: 1;
    }

    25% {
        width: 100%;
        height: 2%;
    }

    100% {
        width: 0%;
        height: 1%;
        opacity: 0;
    }
}
```

After applying the styles, the UI will transition as if it opens from the center of the screen. To “turn off” the TV, we’ll later add the class `screen-off` to the `content-container` via JavaScript to trigger the opposite animation.

#### Slightly adjusting the UI

In the preview, you may notice the bottom-right corner of the UI is slightly cut off due to the plane’s curvature. To fix this, adjust the button’s CSS properties as follows:

```css
.buttons {
    width: 100%;
    position: absolute;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-family: 'Evil Dead';
    bottom: 1vmax;
    right: 1vmax;
    bottom: 3vmax;
    right: 3vmax;
    color: var(--white)
}
```

### Adding the old tv screen noise effect

To add the effect of a game being played on an old CRT TV, let’s add an effect throug css and overlay it on top of the content. We are going to achieve this effect by adding a gradient background to the `overlay` element and animate it’s background position slightly to simulate the lines flickering.

Start by adding a `<div>` with the class `overlay` inside the `content-container`:

```html
<div class="content-container">
    <div class="overlay"></div>
    <!-- Rest of the content -->
```

Now, define the styles for the `overlay` element and add an animation for the static noise effect:

```css
.overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: linear-gradient(rgba(0, 146, 68, 0.15) 30%, rgba(255, 255, 255, 0.15));
    background-size: 100% 20px;
    animation: tv 1s forwards linear infinite;
    z-index: 999;
}

@keyframes tv {
    from {
        background-position: 0% 0%;
    }

    to {
        background-position: 0% -10%;
    }
}
```

Once the styles are applied, the overlay will create a subtle, animated noise effect reminiscent of an old CRT TV.

### Implementing a pause menu to turn off the TV

To simulate the player interacting with the game on the TV, we’ll add a simple pause menu. When the player opens the menu and clicks **Quit**, the TV will turn off.

Begin by adding the HTML for the pause menu

```html
<div class="content-container">
    <div class="overlay"></div>
    <div class="pause-menu">
       <div class="menu-btn play-btn">Play</div>
       <div class="menu-btn quit-btn">Quit</div>
    </div>
    <!-- Rest of the content -->
```

And the styles

```css
.pause-menu {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 4vmax;
    color: var(--white);
    font-weight: bold;
    background-color: rgb(0, 0, 0);
    line-height: 1.5;
    z-index: 1;
}

.pause-menu.open{
    display: flex;
}

.menu-btn:focus{
    color: white;
    outline: none;
}
```

Next, add a visual indicator on the bottom left corner of the screen for the player to know which button to press to open the pause menu:

```html
<div class="main-container">
    <!-- main container content -->
</div>
<div class="pause-text">
    <div>Press "OPTION"</div>
    <div>to pause</div>
</div>
<div class="buttons">
    <span class="rotate-btn hidden buttons-mr-1 flex">
        Rotate Item
        <div class="button-square"></div>
    </span>
    <span class="select-btn buttons-mr-1 flex">
        <div class="button-cross-text">Select Item</div>
        <div class="button-cross"></div>
    </span>
</div>
```

```css
.pause-text {
    width: 100%;
    position: absolute;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    font-family: 'Evil Dead';
    bottom: 3vmax;
    left: 10vmax;
    color: var(--white)
}
```

Now let’s make the menu interactable so we can trigger the `QuitGame` event we defined in Unreal Engine earlier.

First, get references to the pause menu and content container:

```js
let selected = null;
let itemElements = [];

const pauseMenu = document.querySelector('.pause-menu');
const contentContainer = document.querySelector('.content-container');
const pauseMenuClassList = pauseMenu.classList;
const spatialNavigation = interactionManager.spatialNavigation;
```

Update the existing `focusin` event to avoid breaking previous logic when interacting with the pause menu:

```js
document.addEventListener('focusin', ({ target }) => {
    if(target.classList.contains('menu-btn')) return;

    focusedItem.item = Inventory[target.index];
    engine.synchronizeModels();
});
```

Modify the `handleEnterPress` function to handle pause menu interactions:

- The Play button will close the menu.
- The Quit button will trigger the QuitGame event in Unreal Engine and execute the TV’s “turn off” animation.

```js
function handleEnterPress() {
    const activeElementClassList = document.activeElement.classList;

    if (pauseMenuClassList.contains("open")) {
        if(activeElementClassList.contains('play-btn')) {
            pauseMenuClassList.remove("open");
        }
        else if(activeElementClassList.contains('quit-btn')) {
            ppauseMenuClassList.remove("open");
            contentContainer.classList.add('screen-off');
            engine.trigger('QuitGame');
        }

        spatialNavigation.focusFirst("default");
        return;
    }

    if (!selected) return selectItem();
    placeItem();
}
```

Create a function to open the pause menu, initialize [spatial navigation ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/spatial-navigation/), and focus the Play button:

```js
function openPauseMenu() {
    if(selected) return;

    pauseMenuClassList.add("open");
    spatialNavigation.add([{ area: 'pauseMenu', elements: ['.menu-btn'] }]);
    spatialNavigation.focusFirst('pauseMenu');
}
```

Now we need to attach both functions and since the `Tetris UI` supports playstation controller input with the [Interaction manager ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/gamepad/)we can easily extend our logic to be supported by a gamepad,

```js
interactionManager.keyboard.on({
    keys: [KEYS.ENTER],
    callback: handleEnterPress,
    type: 'press',
});

interactionManager.gamepad.on({
    actions: ['playstation.x'],
    callback: handleEnterPress,
});

interactionManager.keyboard.on({
    keys: [KEYS.P],
    callback: openPauseMenu,
    type: 'press',
});

interactionManager.gamepad.on({
    actions: ['playstation.options'],
    callback: openPauseMenu,
});
```

Players can now open the pause menu by pressing `P` on a keyboard or the Start button on a PlayStation controller. The menu allows them to resume the game or quit, triggering the TV “turn off” effect.

With this the UI is completed!

## On this page
