-
Three.js journey fun, positioning.
-
mesh
andcamera
objects are inherited from the baseObject3D
class. which has the propertyposition
. theposition
hasx
,y
andz
properties to control the position on a canvas.x
is right - lefty
is up - downz
is 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
,y
andz
. -
View the a visual helper of the axes with
AxesHelper()
. blue = z , green = y m red = x. The length of the line represent1
unit.
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.scale
which also hasx
,y
andz
properties- it has very similar properties to
position
-
Rotations are slightly harder
- you can do this with either
rotation
orquaternion
- the
rotation
object is an Euler class. This requires you think about what axis the object is rotating on. - To rotate an object you have to use
pi
either3.14159
orMath.Pi
a 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
,y
andz
properties in a different orders. remember how imperative the execution order isrotation.reorder
can you change the rotation orders by applying a string in the order you want e.grotation.reorder('YXZ')
- to work around rotate the
quaternion
is 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 anotherVector3
object. 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.