Unity Recipes - Look Toward Direction of Movement
· updated · Game development
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyController : MonoBehaviour
{
private void Update()
{
smoothLookTowardDirectionOfMovement();
}
void smoothLookTowardDirectionOfMovement()
{
float moveHorizontal = moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
if (moveHorizontal != 0 || moveVertical != 0)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.15F);
}
}
}
In line 19, Quaternion.Slerp takes three arguments: two
quaternions and a float. It interpolates the rotation between the
two quaternions with the speed of the given float value (0.0 is no
movement while 1.0 is instant movement). The code interpolates the
rotation between the current rotation
(transform.rotation) and the movement
rotation(Quaternion.LookRotation) with a speed of
0.15F. This gives the object a smooth turn instead of an instant
turn. The if statement that wraps the code at line 17
keeps the object from instantly flipping or reverting direction when
no inputs are being applied.
For instant (non-smooth) rotation, line 19 can be replaced with the following:
transform.rotation = Quaternion.LookRotation(movement);