We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'd like to move an object from one position to another over a specified period of time in milliseconds, but am thoroughly stuck (maybe because it's Friday night and I have been staring at this screen too long).
I have this code, hacked from one of the examples:
float x,y;
float startX,startY, endX,endY;
float distX, distY;
float percent;
float step = 0.01;
void setup() {
size(800,800);
startX = width/2;
startY = height/2;
endX = 100;
endY = 100;
distX = endX - startX;
distY = endY - startY;
percent = 0;
}
void draw() {
background(255);
percent += step;
if (percent < 1.0) {
x = startX + (percent * distX);
y = startY + (percent * distY);
}
fill(255,150,0);
noStroke();
ellipse(x,y, 50,50);
}
It moves the ball nicely and I can change the step
variable to set the speed, but I really would like to get it so the movement happens over exactly 1000 milliseconds, for example.
Help!
Answers
Please edit your post (upper-right gear) to show the code you are actually using. This is buggy and does not run -- e.g. "step = duration" has no semicolon and refers to a non-variable.
Oops, sorry about that! That was leftover from some attempts to figure this out. Fixed.
A general concept for fitting travel over a path to a time frame is linear interpolation -- in processing, there is a low-level lerp() function. You put in your values (e.g. the beginning and end x of your ball) and an 'amount' value from 0-1, and it gives you the interpolated position between beginning and end values. Think of lerp as a slider -- when it is at 0, your ball is at the beginning, at 1 it is at the end.
Then map your clock (e.g. 1000 milliseconds) to 0-1 when you call lerp() each draw.
Note that draw gets called about 60/second (~1000/60 = ~17 milliseconds) or at frameRate(), so if you are trying to animate over 1000 milliseconds you will get about that many frames of animation.
@jeffthompson -- Here is an example of the concept. Notice how many of your variables are all taken care of by lerp() -- you just need a timeSpan -- and to compute the current timePosition each frame.
Thanks! This makes a ton of sense. I had looked at
lerp()
but couldn't figure out how to map time to it in a simple way – usingfloat timePosition = millis()/timeSpan % 1;
is really elegant.