- Home /
How to rotate a character controller by exactly 90 degrees with one key
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!
Answer by Mehul-Rughani · Oct 04, 2014 at 05:41 AM
Hope You Are Looking For This..using UnityEngine; using System.Collections;
public class Try : MonoBehaviour {
float temp;
bool isRotating;
int horizontalDirection,verticalDirection;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.RightArrow) && !isRotating) {
isRotating = true;
horizontalDirection = 1;
verticalDirection = 0;
temp = 0;
}
if (Input.GetKeyDown (KeyCode.LeftArrow) && !isRotating) {
isRotating = true;
horizontalDirection = -1;
verticalDirection = 0;
temp = 0;
}
if (Input.GetKeyDown (KeyCode.UpArrow) && !isRotating) {
isRotating = true;
verticalDirection = 1;
horizontalDirection = 0;
temp = 0;
}
if (Input.GetKeyDown (KeyCode.DownArrow) && !isRotating) {
isRotating = true;
verticalDirection = -1;
horizontalDirection = 0;
temp = 0;
}
transform.Rotate (Vector3.up * 90 * Time.fixedDeltaTime * horizontalDirection, Space.World);
transform.Rotate (Vector3.right * 90 * Time.fixedDeltaTime * verticalDirection, Space.World);
temp += 90 * Time.fixedDeltaTime;
if (temp >= 90) {
temp = 0;
horizontalDirection = 0;
verticalDirection = 0;
isRotating = false;
}
}
}