-
Three.js journey fun, positioning.
-
meshandcameraobjects are inherited from the baseObject3Dclass. which has the propertyposition. thepositionhasx,yandzproperties to control the position on a canvas.xis right - leftyis up - downzis forward- back- mutating these values is synchronous, so execution order is important. it’s written in a very imperative way.
Useful methods
-
mesh.position.length()returns the length of the object from the center of the scene. -
mesh.position.distanceTo(camera.position)return the distance of the object to a given camera object -
mesh.position.normalise()rounds up the length to whole number. -
mesh.position.set()is a quick way to move the position of an object. it takes 3 argsx,yandz. -
View the a visual helper of the axes with
AxesHelper(). blue = z , green = y m red = x. The length of the line represent1unit.
const axesHelper = new THREE.AxesHelper();
scene.add(axesHelper);
-
normalise your values and stick to it. e,g
1===1km. It can change from project to project, but just be consistent. -
Scaling an object works in the same way:
mesh.scalewhich also hasx,yandzproperties- it has very similar properties to
position
-
Rotations are slightly harder
- you can do this with either
rotationorquaternion - the
rotationobject is an Euler class. This requires you think about what axis the object is rotating on. - To rotate an object you have to use
pieither3.14159orMath.Pia whole rotation ispi x 2 - Warning, you can get into “Gimbal” lock when doing too many rotations. this is where changing the rotations does nothing.
- to work around rotate the
x,yandzproperties in a different orders. remember how imperative the execution order isrotation.reordercan you change the rotation orders by applying a string in the order you want e.grotation.reorder('YXZ')
- to work around rotate the
quaternionis a mathematical way that can get around these gimbal locks. It’s a representation of the rotation which will “just work”. This is a black box for now.
- you can do this with either
-
lookAt()is a really useful method to look directly at anotherVector3object. e.gmesh.position. you can do something like thiscamera.lookAt(mesh.position)so the camera tracks an object. -
3D objects get very complicated, so if you want to create lots of 3d object and group them use
new THREE.Group(). Objects can be added to the group so that they can be rotated and scaled all at the same time.