Hi! I’m super new to Unity and programming in general, and am trying to learn as I go.
I’m trying to make a sprite turn with my input directions, like when I move left using “a”, the sprite points left, and I would like to do it so there are 8 directions (North, northeast, east, southeast, etc.) based off the input.
I tried using Quaternion.Lerp in order to set the rotation and it works. I don’t want to make 8 “if” statements just to figure out where I want to point, so I’m wondering if there’s a better way to use Input.GetAxis data from Vertical and Horizontal and figure out where to point. Hopefully this makes sense.
That code will set the orientation of the transform, it won’t move it. It’s just saying “point the transform’s X axis in this direction”.
You could linearly interpolate it, but for a rotation you probably want a spherical interpolation.
Here’s a bit more complicated version that uses rotations:
public float turnSpeed = 5f;
private void Update()
{
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
// we want to point the X axis in the input direction
Vector3 xAxisDirection = input.normalized;
// the Y axis will be 90 degrees away from the X axis
Vector3 yAxisDirection = Quaternion.Euler(0,0,90) * xAxisDirection;
// the Z axis points forward in 2D
Vector3 zAxisDirection = Vector3.forward;
// this function takes Z axis and Y axis, and gives back the rotation for that orientation
Quaternion newRotation = Quaternion.LookRotation(zAxisDirection, yAxisDirection);
// interpolate rotation over time
transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, turnSpeed * Time.deltaTime);
}