I want to rotate a cube smoothly with the lerp function from its current rotation to a value which would be
x: 0
y: 345
z: 0
How should I approach this? C#
I want to rotate a cube smoothly with the lerp function from its current rotation to a value which would be
x: 0
y: 345
z: 0
How should I approach this? C#
The simplest way is Quaternion.Lerp as answered before and you can convert your target/desired rotation euler angle rotation into quaternion with Quaternion.Euler().
Alternatively, if you want to work with euler angles directly, you can access tranform.eulerAngles and lerp with Mathf.LerpAngle() each angle individually. Note, however, that there are multiple ways in euler angles to represent certain 3D rotations (gimbal lock), so you will need to manually keep track of your current and desired target rotation, lerp that value, and assign it to live transform (otherwise the “real” euler angles can suddenly jump/change at certain overlapping angles). Something like:
public class RotateMe : MonoBehaviour
{
public Vector3 targetAngle = new Vector3(0f, 345f, 0f);
private Vector3 currentAngle;
public void Start()
{
currentAngle = transform.eulerAngles;
}
public void Update()
{
currentAngle = new Vector3(
Mathf.LerpAngle(currentAngle.x, targetAngle.x, Time.deltaTime),
Mathf.LerpAngle(currentAngle.y, targetAngle.y, Time.deltaTime),
Mathf.LerpAngle(currentAngle.z, targetAngle.z, Time.deltaTime));
transform.eulerAngles = currentAngle;
}
}
As POLYGAMe said, uou will use Quaternion.Lerp: Unity - Scripting API: Quaternion.Lerp
But you have to change the code there, so:
transform.rotation = Quaternion.Lerp (transform.rotation, new Quaternion.Euler(transform.rotation.x, 345f, tramsform.rotation.z), Time.deltaTime * speed);
Hope this helps, and if it does, accept the answer
If you are still working on this Rocket, I had the same issue that you had and all it was was this
private Vector3 currentAngle;
public void Start()
{
currentAngle = transform.eulerAngles;
}
public void Update()
{
currentAngle = new Vector3(currentAngle.x, currentAngle.y, 90);
transform.eulerAngles = currentAngle;
}
Hopefully this helps you out!