Besides all the classical designpatterns in js, (re)using a simple underscore object (lodash-style) with useful patterns can be really productive.
square = (x,freq) => ( x & freq )
Sometimes sensors are too noisy (accelerometer/gyroscope), therefore smoothing comes in handy:
function smooth(coef){
this.x = 0
return (x) => (this.x = this.x * coef + x * (1.0-coef))
}
var s = new smooth(0.9)
s(0.1) // 0.009
s(0.8) // 0.088
s(0.8) // 0.160
handy to spawn 3d objects randomly into space, but aligned to a grid and without overlapping other objects.
// usage: snapToGrid({position:[0,0,0],1,1,1,['x','y'],{})
let snapToGrid = (obj, snapX, snapY, snapZ, axes, cache ) => { const pos = AFRAME.utils.clone(obj.position)
pos.x = Math.floor(pos.x / snapX) * snapX //+ data.offset.x;
pos.y = Math.floor(pos.y / snapY) * snapY //+ data.offset.y;
pos.z = Math.floor(pos.z / snapZ) * snapZ //+ data.offset.z;
var hash = String(pos.x+pos.y+pos.z)
obj.position.set( pos.x, pos.y, pos.z )
if( cache[ hash ] ){ // recurse if coordinates already taken (in cache)
let items = []
if( axes.includes('x') items.push({f:'translateX', snap:snapX})
if( axes.includes('y') items.push({f:'translateY', snap:snapY})
if( axes.includes('z') items.push({f:'translateZ', snap:snapZ})
let t = items[Math.floor(Math.random() * items.length)];
obj[ t.f ]( t.snap )
this.snapToGrid(obj, snapX, snapY, snapZ )
}
hash = String(pos.x+pos.y+pos.z) // final coords
cache[hash] = true
}