osa1 feed

THREE.js axis helper

April 17, 2013 - Tagged as: threejs, coffeescript, en.

I’m using THREE.js for a project I’m working on. This is my first experience programming a 3D environment and I’m having hard times wrapping my head around 3D coordinate system.

So I wrote a helper function that draws axis arrows to the scene center to help me see how to translate/rotate my objects.

drawAxisHelpers = (params = {}) ->
    params.radius = params.radius || 0.05
    params.height = params.height || 2
    params.scene  = params.scene  || scene

    arrowGeometry = new THREE.CylinderGeometry 0, 2 * params.radius, params.height / 5

    xAxisMaterial = new THREE.MeshBasicMaterial color: 0xFF0000
    xAxisGeometry = new THREE.CylinderGeometry params.radius, params.radius, params.height
    xAxisMesh     = new THREE.Mesh xAxisGeometry, xAxisMaterial
    xArrowMesh    = new THREE.Mesh arrowGeometry, xAxisMaterial
    xAxisMesh.add xArrowMesh
    xArrowMesh.position.y += params.height / 2
    xAxisMesh.rotation.z  -= 90 * Math.PI / 180
    xAxisMesh.position.x  += params.height / 2
    params.scene.add xAxisMesh

    yAxisMaterial = new THREE.MeshBasicMaterial color: 0x00FF00
    yAxisGeometry = new THREE.CylinderGeometry params.radius, params.radius, params.height
    yAxisMesh     = new THREE.Mesh yAxisGeometry, yAxisMaterial
    yArrowMesh    = new THREE.Mesh arrowGeometry, yAxisMaterial
    yAxisMesh.add yArrowMesh
    yArrowMesh.position.y += params.height / 2
    yAxisMesh.position.y  += params.height / 2
    params.scene.add yAxisMesh

    zAxisMaterial = new THREE.MeshBasicMaterial color: 0x0000FF
    zAxisGeometry = new THREE.CylinderGeometry params.radius, params.radius, params.height
    zAxisMesh     = new THREE.Mesh zAxisGeometry, zAxisMaterial
    zArrowMesh    = new THREE.Mesh arrowGeometry, zAxisMaterial
    zAxisMesh.add zArrowMesh
    zAxisMesh.rotation.x  += 90 * Math.PI / 180
    zArrowMesh.position.y += params.height / 2
    zAxisMesh.position.z  += params.height / 2
    params.scene.add zAxisMesh

drawAxisHelpers function takes named parameters, all optional. radius and height are for sizes of arrows, and scene is the scene object to draw arrows. When isn’t provided, a global scene object is used.

Here’s an example: (you can zoom in/out with mouse scroll, move around with left/right clicks)

In this example I used OrbitAndPanControls class to enable zooming/moving around with mouse. I copied this class from Udacity’s ‘CS291 - Interactive 3D Rendering’ course’s examples. You can see this post’s source to learn more.