Hi there!
I have an object that rotates to different axes.
I use the “Space” button to return it to base coordinates (0,0,0). via Linear Interpolation.
Sometimes it works well, sometimes very strange. What’s wrong with code?
I really appreciate any help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* Rotate object X, Y and Z axes by QWASDE */
public class TableControl : MonoBehaviour
{
public float rotateSpeed = 25f;
private float zInput; // rotate to player and from player
private float xInput; //
private float yInput; // rotate to the left and right
[Header("For Interpolation")]
public Vector3 curRot;
public Vector3 baseRot = new Vector3(0, 0, 0);
public float timeDuration = 5;
public bool checkToStart = false;
[Header("Set Dynamically")]
public Vector3 finRot;
public bool movingToZero = false;
public float timeStart;
void Start()
{
}
void Update()
{
zInput = Input.GetAxis("RotateZ");
xInput = Input.GetAxis("RotateX");
yInput = Input.GetAxis("RotateY");
/* Rotate at any axes */
transform.Rotate(Vector3.right, Time.deltaTime * rotateSpeed * zInput, Space.World);
transform.Rotate(Vector3.down, Time.deltaTime * rotateSpeed * xInput, Space.World);
transform.Rotate(Vector3.back, Time.deltaTime * rotateSpeed * yInput, Space.World);
if (Input.GetKey(KeyCode.Space))
{
movingToZero = true;
timeStart = Time.time;
Debug.Log("time " + timeStart);
}
if (movingToZero)
{
float xAngle = transform.eulerAngles.x;
float yAngle = transform.eulerAngles.y;
float zAngle = transform.eulerAngles.z;
curRot = new Vector3(xAngle, yAngle, zAngle);
float u = (Time.time - timeStart) / timeDuration;
if (u >= 1)
{
u = 1;
}
finRot = (1 - u) * curRot + u * baseRot;
transform.rotation = Quaternion.Euler(finRot);
}
if (transform.rotation == Quaternion.Euler(baseRot))
{
movingToZero = false;
}
}
}