I want to rotate a cube smoothly with 45 degress each time, so if I click on the cube it snaps to 45 degrees and then to 90 degrees and so on till 360. What the problem is it goes not exactly to 45 degrees but 43.4 on the rotation and I want that it goes exactly to 45.
What I tried:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class useObject : MonoBehaviour {
float thisStep = 0f;
GameObject lastHit;
void Start () {
Screen.lockCursor = true;
}
void Update ()
{
if(thisStep == 0 && lastHit != null)
{
float rot = Mathf.RoundToInt(lastHit.transform.rotation.eulerAngles.x);
print("r=" + rot);
if(rot > 10 && rot < 45) // 0
{
lastHit.transform.rotation = Quaternion.Euler(new Vector3(0,0,0));
lastHit.transform.Rotate(new Vector3(Mathf.LerpAngle(0f,90f,Time.deltaTime),0f,0f));
}
else if(rot > 45 && rot < 135) // 90
{
lastHit.transform.rotation = Quaternion.Euler(new Vector3(0,90,0));
lastHit.transform.Rotate(new Vector3(Mathf.LerpAngle(0f,90f,Time.deltaTime),0f,0f));
}
else if(rot > 135 && rot < 225) // 180
{
lastHit.transform.rotation = Quaternion.Euler(new Vector3(0,180,0));
lastHit.transform.Rotate(new Vector3(Mathf.LerpAngle(0f,90f,Time.deltaTime),0f,0f));
}
else if(rot > 225 && rot < 315) // 270
{
lastHit.transform.rotation = Quaternion.Euler(new Vector3(0,270,0));
lastHit.transform.Rotate(new Vector3(Mathf.LerpAngle(0f,90f,Time.deltaTime),0f,0f));
}
else // 0
{
lastHit.transform.rotation = Quaternion.Euler(new Vector3(0,0,0));
lastHit.transform.Rotate(new Vector3(Mathf.LerpAngle(0f,0f,Time.deltaTime),0f,0f));
}
print ("hallo2=" + lastHit.transform.rotation.x);
}
Ray raycast = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit raycasthit = new RaycastHit();
if (Physics.Raycast(raycast, out raycasthit, 1000.0f) && Input.GetMouseButton(0) && thisStep < 360)
{
switch(raycasthit.collider.name)
{
case "Deel1":
case "Deel2":
case "Deel3":
Vector3 rot = new Vector3(Mathf.LerpAngle(0f,90f,Time.deltaTime),0f,0f);
if(thisStep + rot.x <= 360)
{
lastHit = raycasthit.collider.gameObject;
raycasthit.collider.transform.Rotate(rot);
thisStep += rot.x;
}
else if(thisStep + rot.x == 360)
{
lastHit = raycasthit.collider.gameObject;
raycasthit.collider.transform.Rotate(rot);
thisStep -= rot.x;
}
break;
default: print("Unhandled raycastHit " + raycasthit.collider.name); break;
}
}
else if(Input.GetMouseButtonUp(0))
{
thisStep += 0;
}
}
}