Custom JavaScript Components
We continue where we left off in Getting Started.
Overview
Goal of this tutorial is to get you familiar with adding custom logic to your project.
We will be creating two scripts that allow counting the number of frames an object was looked at.
One script will be added to the camera, which will raycast for counting objects. The second is added to an object to do the counting.
Add a Script Path
We need tell the Wonderland Engine where to look for scripts.
Create a new folder js
in your project root directory.
This folder is already added in the default project.
If you ever need to add more folders, open the “Project Settings” view:
Find “Scripting” and with “Add Folder” you can add a script folder:
JavaScript Reloading
To make our workflow as smooth as possibly, the editor will automatically watch changes to your JavaScript files and reparse them on save.
If you have the app running in the browser it will even reload the page for you with the changes sources.
Create a JavaScript Component
Right click the empty space in the “Asset Browser” and add a new JavaScript
component.
Name the component counting-gaze.js
. Make sure to add “.js” when renaming.
By double clicking the file, it will be opened with the application you configured
your system to open .js
files with.
Code
And finally, we fill the component with life. The following code sends out a raycast into the scene every frame:
|
|
For now we are just printing the hit objects names.
Add it to an Object
This component isn’t just run automatically. We need to add it to the camera!
Run
To see the component in action, “Package”, “Start Server” and “Open Browser”.
If you open the JavaScript console with Ctrl+Shift+C
, you will notice the component
has been initialized.
No object names are being printed, though. WL.scene.rayCast()
uses the collision
system, which only works with collider
components. To make sure the raycast hits
something, we need to add more components!
Colliders
Add a child to the postbox object as shown in the following screenshot.
Add a collision
component to it.
Reduce the radius to e.g. 0.15
.
With this set up, we can “Package” and see that the raycast works.
Counting and Displaying
We need to keep track of counts and finally display them in a text component.
Add a “text” component to our “Collider” object and change the text to “0”.
Then add a new JavaScript source file with the name gaze-counter.js
.
|
|
You will notice the msg
param here. It will automatically generate an input
field for us when we add the component to the “Collider” object:
Finally, replace the // TODO
comment in counting-gaze.js
with the following:
Result
“Package” and check the browser. You will now see the final result!
Summary
Wonderland Engine is very extensible with any JavaScript library that runs in the browser.
With the automatic reloading, the workflow is very smooth and allows for quick iterations.