I’ve set up a first person character controller to stick to a grid. Forward/back (omitted for now) move the controller by set amounts, and left/right rotate it by exactly 90 degrees.
Now, because i plan on using 3D audio sources, i’m trying to get the controller to smoothly rotate by 90 degrees, rather than instantly jumping 90 degrees. Below is the code that i’ve come up with. Right is the smooth rotation, but left is still the instant rotation. My problem is that the smooth rotation is always off by a couple of degrees, which varies each time. Also, is there a way to make this rotation take less than a second? This code only seems to accept ints.
// Update is called once per frame
void Update () {
//ROTATION
float rotLeftRight = Input.GetAxis ("Horizontal");
if (Input.GetButtonDown ("Horizontal")) {
if (rotLeftRight > 0)
StartCoroutine (TurnRight (Vector3.up * 90, 1));
if (rotLeftRight < 0)
transform.Rotate (0, 270, 0);
}
}
IEnumerator TurnRight(Vector3 byAngles, float inTime) {
var fromAngle = transform.rotation;
var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
for(var t = 0f; t < 1; t += Time.deltaTime/inTime) {
transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
yield return null;
}
}
I’m still at the beginning of my C# journey, and would appreciate any help on this. I’ve spent a few days searching for my own solution, but to no avail. Maybe i should try a different approach?
Thanks!
This is perfect, thank you!
– rogmidd