5

I'm trying to create a Roulette/CSGO type wheel, I've cobbled together some solutions I've found over the net. However I can't seem to figure out how to handle the animation / slowing down of the wheel to make it look as smooth as possible.

The basic premise is that I will pass in the winning result number, then the wheel will spin for a minimum desired time (_this.spinTime), then after that it "should" gracefully slow down and then of course land on the correct number.

Here's my code so far (i've commented the key area):

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback, element) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

SpinWheel = function(id) {

  var _this = this;

  _this.el = $('.wheel-wrapper');
  _this.speed = 0;
  _this.startTime = new Date();
  _this.items = 20;
  _this.itemsWidth = 50;
  _this.spinTime = 3000;
  _this.running = false;
  _this.motion = 20;
  _this.resultId = id;
  _this.resultOffset = null;

  _this.setup = function() {
    _this.resultOffset = _this.resultId * _this.itemsWidth;
    _this.loop();
  };

  _this.loop = function() {
    _this.running = true;
    (function gameLoop() {
      _this.update();
      //this returns the translateX to 0 once wheel width is met
      if (_this.speed >= (_this.items * _this.itemsWidth + _this.itemsWidth)) {
        _this.speed = 0;
      }
      _this.speed += _this.motion;
      if (_this.running) {
        requestAnimFrame(gameLoop);
      }
    })();
  };

  _this.update = function() {
    var now = new Date();
    _this.el.css({
      'transform': 'translateX(-' + _this.speed + 'px)'
    });
    //the key area!!
    //if the time elapsed it greater than the spin time, start the slowing down
    if (now - _this.startTime > _this.spinTime) {
        //if the x pos == winning pos && the transition speed is at it's slowest
      if (_this.speed == _this.resultOffset && _this.motion == 1) {
      //stop the animation
        _this.running = false;
        //here we increment down the slowing down
      } else if (_this.speed >= _this.resultOffset) {
        if (_this.motion == 2) {
          _this.motion = 1;
        } else if (_this.speed % _this.motion == 0 && _this.motion > 1) {
          _this.motion -= 2;
        }
      }
      return;
    }

  };


  _this.init = function() {
    _this.setup();
  };

  _this.init();

  return _this;

};
//will be passed in: 20 = number of items
var resultId = parseInt(Math.random() * 20);

var wheel = new SpinWheel(resultId);

Feel free to rip it apart, if there is a more ideal solution.

Fiddle Here

As can be seen in the fiddle, it kind of works, but it's just not smooth and inconsistent on how it slows down at times etc... So help would be much appreciated.

Thanks in advance!

0

1 Answer 1

4

You need to implement some friction.

Just multiply the speed by a fraction of the desired friction.

speed = speed * friction

speed = speed * 0.8

Higher the fraction, smaller the friction, and slower the deceleration.


EDIT: in your case you may want to apply friction to your motion value, but I'm not entirely sure without running your code.


EDIT 2:

Ok ran your fiddle and I think this is what you are looking for? https://jsfiddle.net/ywm3zbc4/7/

_this.update = function() {
    var now = new Date();
    _this.el.css({
      'transform': 'translateX(-' + _this.speed + 'px)'
    });
    if (now - _this.startTime > _this.spinTime) {
      if (_this.speed == _this.resultOffset && _this.motion == 1) {
        _this.running = false;
      } else if (_this.speed >= _this.resultOffset) {
         _this.motion = _this.motion * 0.99;
      }
      return;
}

};

I applied the friction to your motion like I mentioned in the previous edit.


EDIT 3 (from comments):

The way to do it is to get the target position, and ease to that while using the modulo of the total width to translate. You can play around with many different animations with this technique, but I settled on the ease-out sine equation.

This can be called a "sliding window animation", think of it as a bar rolling down a track to a specific location.

New fiddle here: https://jsfiddle.net/ywm3zbc4/10/

Here is the meat of it:

// t: current time
// b: start value
// c: change in value
// d: duration
function easeOutSine(t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
}

_this.update = function(rafTime) {
  var deltaTime = rafTime - _this.startTime;
  if (deltaTime >= _this.spinTime) {
    _this.running = false;
    return;
  }
  // t = timeFraction
  var t = easeOutSine(deltaTime, 0, 1, _this.spinTime);
  _this.position = Math.round(t * _this.totalDistance);
  var translateX = _this.position % _this.totalWidth;
  console.log('translateX:', translateX, 'position:', _this.position, 'deltaTime:', deltaTime);
  _this.el.css({
    'transform': 'translateX(-' + translateX + 'px)'
  });
};
9
  • Hi, thanks for your speedy answer, i've had a look and yes it looks way better, now the problem is it doesn't stop on the right number :| Jan 4, 2017 at 15:15
  • Sorry I probably removed too much to get the idea across. Now that I see your resultOffset, what you can do is interpolate to that value after a certain amount of friction. If you are unfamiliar with interpolation, this comment is not the appropriate place to explain. Essentially you have a target position, but you are trying to make it look random, I get it. So you need to loop a few times, slow down with some friction, wait for your target position within a speed threshold, then ease-out the rest of the way.
    – drkibitz
    Jan 4, 2017 at 15:28
  • 1
    I guess something like this would do jsfiddle.net/xareyo/ywm3zbc4/8, as I don't necessarily need to have a pre defined target position (even though I thought that it would be more reliable). I guess I'll have to see. Jan 4, 2017 at 15:44
  • How about you get this value: (wheelSize * totalLoops) + resultOffset. Then you interpolate the total value to that value (from 0 to x). Then you use the modulo of the interpolated "total" value, to translate the wheel correctly. You can use various interpolation methods with this approach, with many different easing equations, but all are the same. You have a current value, a destination value, a total time to get there, and the time of change to return the interpolation.
    – drkibitz
    Jan 4, 2017 at 15:48
  • Just thinking about it, I actually have to specific a target position. Jan 4, 2017 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.