How to determine angle degrees distance of one object from another?
Alright here's what I mean. Say I have this flashlight right? And I have it Flashing light in a direction where I want to see. The Flashing light is the head point. Like the front.
So then I also have this object directly behind me.
So because the object is directly behind that would mean it's 360 degrees angle away from my Flashing Light the head point.
But as I rotate around, the degrees distance from my head point to the object becomes narrower and lesser. Like 270,180,90,45,0 simple like that.
Does anyone know how I would go about this?
I made a box collider to have it be treated as my Flashing Lights Head Point but I don't know to measure the distance in degrees and so on.
Any help would be good.
: )
Answer by burtonposey · Sep 20, 2015 at 10:23 AM
I am pretty sure that directly behind you would be 180 degrees.
You want to use Vector3.Angle . It takes in a from Vector3 and a to Vector3 and returns the angle between the two. If I understand you correctly, you'll have your head angle which is, at the start, this flashing light reference point. If you're staring at that, it's effectively your Camera's transform.forward. This is your from. Your to is your target's position - the camera's transform.position.
So if this script were to be attached to your camera it would look like this:
using UnityEngine;
using System.Collections;
public class AngleTest : MonoBehaviour {
public Transform targetTransform;
// Update is called once per frame
void Update ()
{
if (targetTransform != null)
{
float angleToTarget = Vector3.Angle(transform.forward, targetTransform.position - transform.position);
Debug.Log("Angle to target is: " + angleToTarget);
}
}
}
Aww Yeah lol. 180.
Thanks though dude.
I tried this before but I didn't think I needed the transform.forward as well.
Well this does work, in some.. way.
For some reason when I distant my object farther and closer the numbers still range up and down. Like it's good. but as I get dead closer while in front of it, it ranges to about 90 until it totally reaches the other side. and as I get farther while in front, it ranges around 0. but when i'm directly in front of it at a good distance, it becomes around 6 - 8.
It's weird. I tried Localposition but that seem to only decrease the number by 2 points.
Hmm.. Any idea why it's doing this? $$anonymous$$ind of annoying.
Haha Nvm dude, this did it. I did a standard Cube Test and I figured out why it did that.
It was because both objects weren't lined up in the same Z Axis (Up & Down Axis)
Thanks $$anonymous$$an!
Your answer
![](https://koobas.hobune.stream/wayback/20220612034404im_/https://answers.unity.com/themes/thub/images/avi.jpg)