Back to Content
3D Movement with JavaScript
This example shows how to move a 3d object in a Coppercube scene using JavaScript. This is only useful when using the Windows (.exe) or MacOS (.app) target of CopperCube. If you are looking for the WebGL version,
take a look here.
To start, do the following:
- Start the CopperCube editor and create a new Free 3D scene. Use the scene as it is, usually, there should be a skybox and a cube named 'cubeMesh1' in that scene.
- Add a plane using the 'Create a plane' button on the 'Scene editing' tab with he default values.
- Move the plane a bit so that the scene looks similar to this:
The scene for this example.
- Save the scene as 'test.ccb'
- Publish it as Windows (.exe) [or Mac OS X (.app) file], using either 'Tools -> Test as Windows Application' or 'File -> Publish -> Publish as Windows Application'. A file named test.exe should now be written out, where you saved the test.ccb file.
- Now create an empty text file where your saved the test.ccb file and name it 'test.js'. Edit this file with your favorite text editor (recommended: Notepad++, it
supports JavaScript syntax highlighting). When publishing your file now as Windows .exe, CopperCube will include this
script into the .exe file and use it as main script.
Write the following code into your .js file
// register key events
ccbRegisterKeyDownEvent("keyPressedDown");
function keyPressedDown(keyCode)
{
if (keyCode == 88)
{
// the user pressed the key 'X', move the 'cubeMesh1' scene node a bit up
var cube = ccbGetSceneNodeFromName("cubeMesh1");
var pos3d = ccbGetSceneNodeProperty(cube, "Position");
pos3d.y += 2;
ccbSetSceneNodeProperty(cube, "Position", pos3d);
}
}
When you now start the application again (Tools -> 'Test As Windows Application (.exe)') the cube will move up every time you press 'X'.
This example works by accessing the JavaScript api. You can manipulate all aspects of the 3D scene with this API: textures, materials, positions, objects etc. For a full reference to all functions, see the JavaScript Scripting reference.