33 lines
1 KiB
JavaScript
33 lines
1 KiB
JavaScript
function filter(p) {
|
|
|
|
/* Clamp velocity to maxVelocity units/second. Zeroing each component of acceleration keeps us from slamming.*/
|
|
var maxVelocity = 5;
|
|
function sign(val) {
|
|
if (val > 0) {
|
|
return 1;
|
|
} else if (val < 0) {
|
|
return -1;
|
|
} else {
|
|
return 0;
|
|
}
|
|
}
|
|
if (p.velocity) {
|
|
/* Random near-zero value used as "zero" to prevent two sequential updates from being
|
|
exactly the same (which would cause them to be ignored) */
|
|
var nearZero = 0.0001 * Math.random() + 0.001;
|
|
if (Math.abs(p.velocity.x) > maxVelocity) {
|
|
p.velocity.x = sign(p.velocity.x) * (maxVelocity + nearZero);
|
|
p.acceleration.x = nearZero;
|
|
}
|
|
if (Math.abs(p.velocity.y) > maxVelocity) {
|
|
p.velocity.y = sign(p.velocity.y) * (maxVelocity + nearZero);
|
|
p.acceleration.y = nearZero;
|
|
}
|
|
if (Math.abs(p.velocity.z) > maxVelocity) {
|
|
p.velocity.z = sign(p.velocity.z) * (maxVelocity + nearZero);
|
|
p.acceleration.z = nearZero;
|
|
}
|
|
}
|
|
|
|
return p;
|
|
}
|