I want to code speedometer for three js
codes:
function calculateSpeed(obj) {
//here is input of obj
this.obj = obj;
this.oldSpeed = null;
this.nowSpeed = null;
this.time = 0;
this.calculateNow = function(deltaTime) {
this.delta = deltaTime - this.time;
this.nowSpeed = this.obj.position.clone();
if (this.delta > 2500) {
this.oldSpeed = this.obj.position.clone();
this.time = deltaTime;
}
}
this.getSpeed = function() {
if (this.oldSpeed) {
return {
x: this.nowSpeed.x - this.oldSpeed.x,
y: this.nowSpeed.y - this.oldSpeed.y,
z: this.nowSpeed.z - this.oldSpeed.z
};
} else {
return null;
}
}
}
usage:
const calculateSpeedOfCar = new calculateSpeed(scene.getObjectByName("car"));
calculateSpeedOfCar.calculateNow(performance.now());
const speed = calculateSpeedOfCar.getSpeed();
if(speed){
console.log(speed);
}
but result of “console.log” is always,
{x: 0, y: 0, z: 0}
{x: 0, y: 0, z: 0}
{x: 0, y: 0, z: 0}
{x: 0, y: 0, z: 0}
{x: 0, y: 0, z: 0}
…
Thanks for now