DOCS

Add interactivity

The objective of this section will be to set the color of the Big Teapot by clicking on either of the two small ones.

Picking & Set component value

  • Go back to your text editor to add some interactivity.

  • Add an onClick function to identify the clicked entity during a click event. Copy paste the script just under the <body> tag.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <script>
    async function onClick(event) {
    const target = await SDK3DVerse.engineAPI.castScreenSpaceRay(
    event.clientX,
    event.clientY
    );
    if (!target.pickedPosition) return;
    const clickedEntity = target.entity;
    console.log(clickedEntity);
    };
    </script>
  • Replace the canvas section in your text editor with this new code.

    1
    2
    3
    4
    5
    6
    <canvas
    id="display-canvas"
    class="display-canvas"
    oncontextmenu="event.preventDefault()"
    onclick="onClick(event)"
    ></canvas>

This new code is attached to our function to the onClick event.

Use the SDK to set a Component’s value

The next step is to retrieve the material_ref value of the entity clicked on, and set it to the big Teapot. Once again, in this example, it is easier to copy and paste the onClick async function to replace the code. Once done, your changes will be made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
async function onClick(event) {
const target = await SDK3DVerse.engineAPI.castScreenSpaceRay(
event.clientX,
event.clientY
);
if (!target.pickedPosition) return;
const clickedEntity = target.entity;
const rootEntities = await SDK3DVerse.engineAPI.getRootEntities();
const bigTeapotEntity = rootEntities.find(
(e) => e.getName() === 'Big_teapot_mesh'
);
if (clickedEntity.getID() !== bigTeapotEntity?.getID()) {
const clickedMaterialRef = clickedEntity.getComponent('material_ref');
bigTeapotEntity.setComponent('material_ref', clickedMaterialRef);
}
};
</script>

Clicking on either of the two small teapots should update the big one.

In the end your html file should look like this:

Previous
Update material