Handling 3D Cursor Clicks

Interacting with the 3D cursor is a fundamental building block for building floating menus, linking to other scenes and otherwise interacting with a 3D environment in a simple way.

This tutorial shows how to handle 3D cursor clicks. We skip setup of the 3D cursor, as that is already set up for you in the “VR” project template when creating a new project.

Components 

The components used in this setup are the cursor, cursor-target and collision.

We will also add a custom component log-on-click for the specific behaviour we want when the object is clicked.

Setup in Editor 

In the editor attach two components to the object that you want to make clickable: collision and cursor-target.

collision specifies the area which should be clickable, once added, you’ll see a green outline indicate the shape that can be clicked on. You can change the collision shape of the component to match your object closest. (Triangle meshes are currently not supported.)

cursor-target allows adding JavaScript code for various cursor events.

Custom Behaviour 

While these components allow us to set up custom behaviour, by themselves, they only change the visual behaviour of the cursor: the cursor object will now appear when pointing at the clickable object.

To add behaviour on click, we add a custom JavaScript component:

 1import {Component, Property} from '@wonderlandengine/api';
 2
 3extends class LogOnClick extends Component {
 4    static TypeName = 'log-on-click';
 5
 6    static Properties = {
 7        message: Property.string("It was clicked!"),
 8    };
 9
10    start() {
11        /* Get a reference to the "cursor-target" component */
12        const target = this.object.getComponent('cursor-target');
13
14        target.addClickFunction(this.onClick.bind(this));
15    }
16
17    onClick() {
18        /* Print the message that was configured in the editor) */
19        console.log(this.message);
20    }
21}

Once that component is added, you can run the project in the browser and when the object is clicked, a message should appear in the Browser Console.