Skip to main content
2 of 3
added 35 characters in body
badweasel
  • 2k
  • 2
  • 18
  • 24

Sorry my answer is for general coding not specific to three.js. I'm an OpenGL iOS coder. But I would think the techniques would apply.

The way I do it (in pseudo code) is:

displayLoop() {
    timeThisRound = date();
    delta = timeThisRound - timeLastRound;
    updateElementWithDelta(delta);
    updateBasedOnTime();
    timeLastRound = timeThisRound;
}

Then call that function on your display loop, either 30 or 60 fps. If the date() function returns time in seconds then delta will be a fraction of a second.

Then if an object is traveling 5 px per second you just set velocity = 5;

Then in the updateGameWithDelta() you'd do:

position = position + velocity*delta;

Since delta is in parts of a second and velocity is in pixels per second, multiplying them together will give you pixels to move for that fraction. Just like hours * miles per hour gives you miles traveled in that number of hours.

You can also do moves based on time alone, which I do a lot.

So if you have a move you want to take 2 seconds you could first set up:

duration=2.0;
startPosition=123.0;
endPosition=456.0;
startTime= timeThisRound + 1.0;

Then in updateBasedOnTime() you'd do:

percentThruMove = (timeThisRound - startTime) / duration;

(timeThisRound - startTime) tells you many things. First if the move hasn't started yet it will be less than 0, so the position would need to stay at the startPosition. if it's bigger than duration the move should have ended and it should be at the ending position. In between the two it is a percentage through the move.

So clamp it to 0-1, and then set the position:

clamp(percentThroughMove, 0,1);
travelDistance = endPosition - startPosition;
currentPosition = startPosition + percentThroughMove * travelDistance;

I also usually set up a trigger to end the move checking. So instead of using a clamp function I do ifs:

if(percentThroughMove<0.0)
    currentPos = startPos;
elseIf(percentThroughMove>1.0) {
    currentPos = endPos;
    moving = no;
}
else {
    travelDistance = endPosition - startPosition;
    currentPosition = startPosition + percentThroughMove * travelDistance;
}

The cool thing with this method is that you also have an opportunity to use a tween instead of a linear move. Like instead of *percent do percentpercent and the move will ease in.

badweasel
  • 2k
  • 2
  • 18
  • 24