Chapter 6: User interface (UI)

Many games rely on showing some kind of UI on top of the 3D game, so let’s try adding some basic UI to our game.

Showing the player’s position

Switch to client.rs, and add the following:


#![allow(unused)]
fn main() {
#[element_component]
fn PlayerPosition(hooks: &mut Hooks) -> Element {
    let pos = use_entity_component(hooks, player::get_local(), translation());
    Text::el(format!("Player position: {}", pos.unwrap_or_default()))
}
}

In-depth: UI in Ambient is loosely inspired by React. See the UI reference documentation for more information.

Tip: See the UI examples to learn how to use layout, buttons, editors and much more.

And then add this to the main function in client.rs:


#![allow(unused)]
fn main() {
PlayerPosition.el().spawn_interactive();
}

You should now see something like this:

UI

Source: The complete code for this chapter can be found here.

Challenge: Try adding a Button, which sends a message to the server and teleports the player somewhere else when clicked. You may find Chapter 4, the button example and the todo example useful.

Source: The complete code for this challenge can be found here.

⇾ Chapter 7: Deploying