I am trying to make a top-down game like Metal Gear Solid 1 and I want my player charter to look at the way he is moving but all the ways I have found online don’t work for me so I am trying to make my own here is what I have so far.
Use Quaternion.LookRotation to generate a Rotation Quaternion you can assign to your transform. You can also use the Vector3.right and .forward constants to build a matching vector a little more conveniently than trying to build a vector from scratch like you did (which can get confusing - you’re not stupid :). You tried to do it with Euler Angles, that’s a little harder and generally Quaternions are always preferable. With the Eulers, you could use Vector3.SignedAngle(from, to) to get your angle. I advise against it.
Recommended way:
using UnityEngine;
public class SimpleLookRotation : MonoBehaviour
{
private void Update()
{
// Calculate World-Space Standard Coordinate direction from the input.
var inputDirection = Input.GetAxis("Vertical") * Vector3.forward +
Input.GetAxis("Horizontal") * Vector3.right;
//If user isn't actively looking with the controller, abort.
if (inputDirection.magnitude < 0.1f) return;
//Generate rotation and apply it to the transform.
transform.rotation = Quaternion.LookRotation(inputDirection);
}
}
This is the BAD way:
using UnityEngine;
public class SimpleLookRotation : MonoBehaviour
{
private void Update()
{
// Calculate World-Space Standard Coordinate direction from the input.
var inputDirection = Input.GetAxis("Vertical") * Vector3.forward +
Input.GetAxis("Horizontal") * Vector3.right;
//If user isn't actively looking with the controller, abort.
if (inputDirection.magnitude < 0.1f) return;
//This is not the best way to do it, but to get the angle from a direction, use Vector3.SignedAngle (Mathf.Atan2 is of limited use)
var eulerAngles = new Vector3(0, Vector3.SignedAngle(Vector3.forward, inputDirection, Vector3.up), 0);
//Generate rotation and apply it to the transform.
transform.eulerAngles = eulerAngles;
}
}
Protip:
You probably want to smooth out your rotation a little, for a start you can use this (use a number > 0 and <= 1 to smooth it, higher numbers turn faster):
//Generate rotation, smooth it from the previous, and apply it to the transform.
var softRotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputDirection), 0.2f);
transform.rotation = softRotation;