Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

8 Directional sprite in 3d world, how to retrieve angle?

$
0
0
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: using UnityEngine; using System.Collections; public class LookDirection : MonoBehaviour { string curDir; Transform player; public float angle; Vector3 direction; public Renderer spriteObj; public Material F; public Material FR; public Material R; public Material BR; public Material B; public Material BL; public Material L; public Material FL; void Awake () {player = GameObject.FindWithTag("Player").transform;} void Start () {StartCoroutine("CalculateDirection");} IEnumerator CalculateDirection () { while(true){ direction = player.transform.position - transform.position; angle = Mathf.Atan2(direction.x,direction.z) * Mathf.Rad2Deg; ChangeDirection(angle.ToString("#00")); yield return null; } } void ChangeDirection (string dir) { switch(dir){ case "90": Debug.Log ("Forward"); spriteObj.renderer.sharedMaterial = F; break; case "135": Debug.Log ("Forward Left"); spriteObj.renderer.sharedMaterial = FL; break; case "45": Debug.Log ("Forward Right"); spriteObj.renderer.sharedMaterial = FR; break; case "-180": Debug.Log ("Left"); spriteObj.renderer.sharedMaterial = L; break; case "180": Debug.Log ("Right"); spriteObj.renderer.sharedMaterial = R; break; case "-90": Debug.Log ("Backward"); spriteObj.renderer.sharedMaterial = B; break; case "-135": Debug.Log ("Backward Left"); spriteObj.renderer.sharedMaterial = BL; break; case "-45": Debug.Log ("Backward right"); spriteObj.renderer.sharedMaterial = BR; break; } } } 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?

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>