So i have a basic 2D movement script, i would like to have it so it slight rotates right when moving right and slightly rotate when moving left. But once the buttons used to move are released I would want it to return to it’s original angle. I just do have any idea on how to go about this. Any insight would be great.
You could set a target angle with your input, and then use Mathf.MoveTowardsAngle or similar functions.
Something like this (psuedo code)
if (left)
target = -45;
if (right)
target = 45;
angle = Mathf.MoveTowardsAngle(angle, target, speed * Time.deltaTime);
Here’s an example using Mathf.SmoothDampAngle to give a smooth Z axis rotation. You can setup a bunch of different parameters and press A/D keys (it uses horizontal axis by default). You can also override the tilt with a script of your choice. Just set .tilt to a value between -1 and 1. 0 is forward. The script will overwrite rotation so if you have any other script that is setting rotation you have to modify the code or make either of the scripts a child of the other.
using UnityEngine;
public class Rotate2D : MonoBehaviour
{
// Max tilt angle
[Range(0, 360)]
public float tiltAngle = 45;
// Degrees per second
[Range(0, 720)]
public float speed = 360f;
// Smaller values is snappier
[Range(0.01f, 1)]
public float smoothTime = 0.1f;
// For the lazy, some kind of def. impl.
public bool useHorizontalAxis = true;
// Provided by script if not useHorizontalAxis
[Range(-1, 1)]
public float tilt;
// The current rotation in angles around Z axis
[HideInInspector]
public float angle;
// The current angular velocity
[HideInInspector]
public float velocity;
void Update()
{
DefaultTiltBehaviour();
UpdateLocalRotation();
}
void DefaultTiltBehaviour()
{
if (useHorizontalAxis)
tilt = -Input.GetAxisRaw("Horizontal");
}
void UpdateLocalRotation()
{
float target = tiltAngle * Mathf.Clamp(tilt, -1, 1);
angle = Mathf.SmoothDampAngle(angle, target,
ref velocity, smoothTime, speed, Time.deltaTime);
transform.localRotation = Quaternion.Euler(0, 0, angle);
}
}