# Would you call this way to measure velocity "correct"?

``````float x;
float playbackSpeed;
float x_po, pr_x, pa_x, x_d;
float prevTime = 0;
float dt, velocity = 1;
float currTime;

void setup() {
size(640, 360);
background(255);
}

void draw() {
x_po+=10; // X1-POSITION
if (x_po > width) // CONDITIONAL STATEMENT FOR RESETTING THE X-POSITION
x_po = 0;
x_d = abs((pa_x-x_po));  // CALCULATE THE PAST-X AND PRESENT-X DIFFERENCE

println("x_po = "+x_po); // PRINT X-POSITION
println("pa_x = "+ pa_x); // PRINT PAST-X POSITION
println("x_d = "+x_d); // DIFFERENCE
pa_x = x_po; // SAVE CURRENT-X VALUE INTO PAST-X VALUE

println("");

currTime = millis(); // TAKE TIME
if (x_d != 0) { // IF THERE IS MOVEMENT D CALCULATE DELTA TIME
dt = abs(prevTime-currTime);
} else if (x_d == 0) { IF THERE IS NO MOVEMENT DO NO CALCULATE DELTA TIME
dt = 0.1;
}
println("currTime"+currTime);  //PRINT PRESENT TIME
println("prevTime"+prevTime); // PRINT PAST TIME
println("dt ="+dt);  //PRINT DELTA TIME
velocity =x_d/(dt/1000); // CALCULATE DELTA X/DELTA TIME = VELOCITY
println("Velocity= "+velocity);  // PRINT VELOCITY
prevTime = currTime; // SAVE OLD PRESENT TIME INTO PREV TIME.
float velocity_c = map(velocity, 0, 1000,0,100); // CONVERT VELOCITY INTO A MORE "UNDERSTANDABLE" VALUE.
velocity_c = constrain(velocity_c, 0, 100); // CONSTRAIN NEW VELOCITY VALUE
println("velocity_c"+velocity_c);  // PRINT NEW CONSTRAINED VELOCITY VALUE

fill(255, 0, 0); // RED
ellipse(x_po, height/2, 45, 45); // DISPLAY MY X-1 COORDINATE AS A BALL

println("");
}
``````

Taking into account

• currTime is always greater than prevTime
• and if x_d != 0 then the else statement is only executed if x_d ==0, no need to test again

the code becomes

``````if (x_d != 0) { // IF THERE IS MOVEMENT D CALCULATE DELTA TIME
dt = currTime - prevTime;
} else  {  //IF THERE IS NO MOVEMENT DO NO CALCULATE DELTA TIME
dt = 0.1;
}
``````

Also need to initialise prevTime and currTime in setup

``````void setup() {
size(640, 360);
background(255);
currTime = prevTime = millis();
}
``````

Don’t assume prevTime is actually zero, depends on how much work is done in `setup`

The technique you are using will compensate for changes in framerate so is good 2 Likes

quark!, thank you so much for your review, I will make sure to learn and implement all the things you’ve mentioned, thanks for your time and advice Hello,

This helps to see the status of frameCount and millis() in setup() and draw():

``````void setup()
{
frameRate(1); // I slowed this down for testing
currTime = prevTime = millis();
println(frameCount, currTime, prevTime, dt);
}

void draw()
{
currTime = millis();
dt = currTime - prevTime;
println(frameCount, currTime, prevTime, dt);
prevTime = currTime;
}
``````

I also slowed down frameRate() in this example for testing.

I used variable names and suggestions in topic.

@G03TH3 I also provided an example of how to properly format code. Hint.

https://discourse.processing.org/faq#format-your-code

`:)`

1 Like