Reputation:
I want to detect if the camera if facing Left/Right/Forward/Back. I have started with a script but it only points to the right side. How do I determine the axis at which the camera faces?
void Update ()
{
Vector3 dir = Camera.main.transform.forward;
float absX = Mathf.Abs (dir.x);
float absY = Mathf.Abs (dir.y);
float absZ = Mathf.Abs (dir.z);
if (absX > absY && absX > absZ)
{
if (absX > 0f)
{
Debug.Log("RIGHT");
}
else
{
Debug.Log("LEFT");
}
}
Upvotes: 0
Views: 163
Reputation: 90580
Well an absolute value in mathematics and used by you in
absX = Mathf.Abs (dir.x);
will always be a positive value.
What you rather want to use would be the original dir.x
// in general you should not use Camera.main repeatedly!
// if possible already reference it here
[SerializeField] private Camera _camera;
// Otherwise get it ONCE on runtime
private void Awake()
{
if(!_camera) _camera = Camera.main;
}
void Update ()
{
Vector3 dir = _camera.transform.forward;
float absX = Mathf.Abs (dir.x);
float absY = Mathf.Abs (dir.y);
float absZ = Mathf.Abs (dir.z);
if (absX > absY && absX > absZ)
{
if (dir.x >= 0f)
{
Debug.Log("RIGHT");
}
else
{
Debug.Log("LEFT");
}
}
else if(absY > absZ) // absY > abs X is already implicit
{
if (dir.y >= 0f)
{
Debug.Log("UP");
}
else
{
Debug.Log("DOWN");
}
}
else // both absZ > absY && absZ > absX are implicit
{
if (dir.z >= 0f)
{
Debug.Log("FORWARD");
}
else
{
Debug.Log("BACKWARD");
}
}
}
Upvotes: 1