Back to Content

3D Collision with JavaScript

This example shows how to test a collision between the mouse cursor and 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:

The scene for this example.

Use the following code:
// register for the drawing event

function onFrameDrawing()
	var mouseX = ccbGetMousePosX();
	var mouseY = ccbGetMousePosY();
	// test collision

	var cube1 = ccbGetSceneNodeFromName("cubeMesh1");	
	var cube2 = ccbGetSceneNodeFromName("cubeMesh2");	
	var endPoint3d = ccbGet3DPosFrom2DPos(mouseX, mouseY);
	var startPos3D = ccbGetSceneNodeProperty(ccbGetActiveCamera(), "Position");
	var cube1Hovered = 
	 ccbDoesLineCollideWithBoundingBoxOfSceneNode(cube1, startPos3D.x, startPos3D.y, startPos3D.z,
	                                              endPoint3d.x, endPoint3d.y, endPoint3d.z);
	var cube2Hovered = 
	 ccbDoesLineCollideWithBoundingBoxOfSceneNode(cube2, startPos3D.x, startPos3D.y, startPos3D.z, 
	                                              endPoint3d.x, endPoint3d.y, endPoint3d.z);
	ccbSetSceneNodeMaterialProperty(cube1, 0, "Wireframe", cube1Hovered);
	ccbSetSceneNodeMaterialProperty(cube2, 0, "Wireframe", cube2Hovered);
When you now start the application again (Tools -> 'Test As Windows Application (.exe)'), this will turn on the wireframe mode for the cube where the mouse pointer is over. The result should look like this:

The 3d object where the mouse cursor is over will be drawn in wireframe mode.

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.