I’m trying to do an 8 directional sprite in a 3d world like Doom. I managed to get it almost wworking, but my script is not very precise as ti try to retrieve absolute angles, and if the player move too fast sometime it skips part of the code, this is my actual script:
UPDATED With Professor Snake solution and Zeh suggestions:
using UnityEngine;
using System.Collections;
public class LookDirection : MonoBehaviour {
Transform player;
public float angle;
Vector3 direction;
public Renderer spriteObj;
public Material[] mat;
void Awake () {player = GameObject.FindWithTag("Player").transform;}
void Update () {
direction = player.transform.position - transform.position;
angle = Mathf.Atan2(direction.x,direction.z) * Mathf.Rad2Deg;
ChangeDirection ();
}
void ChangeDirection () {
if (angle < 0) angle += 360; // Just in case
spriteObj.renderer.sharedMaterial = mat[(int)Mathf.Round(angle / 360f * mat.Length) % mat.Length];
}
}
Consider that the public Material variables are just for testing now to see if it changes properly.
So as you see in the coroutine I just send the angle as string with the first 2 digits only on the overload method of the function ChangeDirection. And the switch check when the angle reach a certain angle, but is not that precise and sometime as I saied before it skips the angle strings.
Any suggestion on a better approach to get a precise angle reference?
Screenshot of what I’m doing:
