system
1
Hi,
I have a spaceship that rotates on the z axis with a max of 30 degrees when the Horizontal axis is held down to give the effect of roll like an airplane. How can I make my object rotate back to 0 degrees when the Horizontal axis is released? So the object only rotates while the left/right keys are held and then it slowly rotates back to 0 when these keys are let go?
Cheers.
How about this- instead of using the Horizontal axis directly, have the Horizontal axis define a “target roll”- this determines how far you want the spaceship to bank. Then in your Update function interpolate between your current roll and the target roll using a function like Mathf.Lerp or Vector3.Lerp. Or, better still, you could weight it so that the interpolation amount changes depending on how much of the axis is pressed- so that if the axis is at full lock it interpolates fast, and if the axis is at zero it interpolates slowly, something like this-
// This is the maximum angle that your ship will rotate to (assign it in editor)
public float maxAngle = 30;
// This is the stored angle that your ship is at
float currentAngle = 0;
void Update()
{
// This makes your angle somewhere between -30 and 30 degrees
float targetAngle = Input.GetAxis("Horizontal") * maxAngle;
// This makes the interpolation faster when the input is pressed down,
// making sure that the value is always positive.
float interpolationSpeed = 1 + (Mathf.Abs(Input.GetAxis("Horizontal") * 10));
// This smoothly sets the current angle based on the input
currentAngle = Mathf.Lerp(currentAngle, targetAngle, interpolationSpeed);
// replace this with however you implement the final value
transform.rotation = Quaternion.Euler(0, 0, currentAngle);
}