Speedometer calculating

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

I fixed the about the code style problem, dude hofk
Thanks for your feedback

1 Like

I don’t know how you want to use it, but maybe my variant will help you.

See Showrooms easy to generate from data of a construction drawing or dimensional sketch - now on Github

use SHOWROOM

Double-click on the central circle in the control and the speedometer will appear. Double-click again and it will disappear.

view-source:https://hofk.de/main/threejs/showroom/showroomAreaControl.js

1 Like

Simple example: AreaControl

from Circular control used for walkable areas control

1 Like