# 2D wheel spin

First, this is a 2D game. I need to spin a sprite a set amount of degrees and then have it slowly stop with a little bounce back easing (like a roulette wheel). I need it to spin the same amount (degrees) and take the same amount of time on each spin. Anyone have some code to do this?

Thanks…

Given what you are trying to achieve, my first thought is an AnimationCurve. The AnimationCurve class allows you to edit a curve that you can then apply in your calculations. Here is a bit of code to get you started:

``````#pragma strict

var ac : AnimationCurve;
private var spinning = false;

function DoSpin(time : float, maxAngle : float) {
spinning = true;
var timer = 0.0;
var startAngle = transform.eulerAngles.z;

while (timer < time) {
var angle = ac.Evaluate(timer/time) * maxAngle;
transform.eulerAngles = Vector3(0.0, 0.0, angle + startAngle);
timer += Time.deltaTime;
yield;
}
transform.eulerAngles = Vector3(0.0, 0.0, maxAngle + startAngle);
spinning = false;
}

function Update() {
if (Input.GetKeyDown(KeyCode.Space) && !spinning) {
DoSpin(3.0, 270.0);
}
}
``````

Note once this script is attached, you can click on the ‘ac’ variable and edit the curve. And here is a shot of the animation Curve.

Note that the end point of the curve should be as close to (1.0, 1.0) as you can make it. Also note the high point of the graph is a above 1.0. This combination will cause the spinner to go past the target degrees and then return.

public IEnumerator DoSpin(float time, float maxAngle)
{
DateTime startSpinTime = System.DateTime.Now;
spinning = true;
float timer = 0.0f;
float startAngle = wheel.GetComponentInChildren().eulerAngles.z;

``````while (timer < time)
{
float currentTime = (float)(System.DateTime.Now - startSpinTime).TotalSeconds;
float acceleration = 1 * currentTime;
float angle = ac.Evaluate(timer/time) * maxAngle;

wheel.GetComponentInChildren<RectTransform>().eulerAngles = new Vector3(0.0f, 0.0f, -(angle + startAngle));

timer += (Time.deltaTime*acceleration);

yield return 0;
}

wheel.GetComponentInChildren<RectTransform>().eulerAngles = new Vector3(0.0f, 0.0f, -(maxAngle + startAngle));
spinning = false;
``````

}

This will also allow you to accelerate and decelerate based on defined ‘acceleration’
This code spins anti clockwise so just subtract 360f to whatever angle you want to stop.
Thanks to main robertbu for the important bit above.