Hello. I currently have a few scripts, the main one I have inserted. Essentially they are old-school angle based sprite billboarding for multi-directional sprites. It works perfectly except for the fact that regardless of the orientation of the sprite object, the angle is still the same. I need the angle to be relative to the gameObject.transform.forward but so far, nothing I’ve done has worked.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class AngleCalculator : MonoBehaviour
{
public Animator objectAnimator;
private SpriteRenderer spriteRenderer;
private GameObject cameraParent;
private Vector3 localPosition;
private Vector3 cameraPosition;
private float localX;
private float localZ;
private float cameraX;
private float cameraZ;
public float angle;
void Awake(){
cameraParent = GameObject.Find("Player");
objectAnimator = gameObject.GetComponent<Animator>();
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
}
void Update(){
localPosition = gameObject.transform.position;
localX = localPosition.x;
localZ = localPosition.z;
cameraPosition = cameraParent.transform.position;
cameraX = cameraPosition.x;
cameraZ = cameraPosition.z;
angle = Mathf.Rad2Deg * Mathf.Atan2((cameraZ-localZ), (cameraX-localX));
if (angle < 0){
angle = 360 + angle;
}
Vector3 lookDirection = new Vector3(cameraParent.transform.forward.x, 0, cameraParent.transform.forward.z);
transform.LookAt(transform.position + lookDirection);
if (angle >= 202 && angle <= 337.8){
spriteRenderer.flipX = true;
}
else {
spriteRenderer.flipX = false;
}
objectAnimator.SetFloat("ViewAngle", angle);
}
public void OnDrawGizmos(){
if (!Application.isPlaying){
SceneView sceneView = GetActiveSceneView();
if (sceneView){
Vector3 lookDirection = new Vector3(sceneView.camera.transform.forward.x, 0, sceneView.camera.transform.forward.z);
transform.LookAt(transform.position + lookDirection);
}
}
}
private SceneView GetActiveSceneView(){
if (EditorWindow.focusedWindow != null && EditorWindow.focusedWindow.GetType() == typeof(SceneView))
return (SceneView)EditorWindow.focusedWindow;
return null;
}
}