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.
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!