- Home /
Degree measurement between two objects : bug
Hello everybody,
i am in big need to measure the relation between object A and Object B in terms of degrees. What do i mean? Imagine a compass. You stand somewhere (your Character Object), you rotate and it shows towards north --> you can now how your relation is towards north. In my implementation north would be exactly 180 degree: than i would face it. If i stand to the opposite it would be 0.
Now i don't want the degree relation between the Character and North, but between him and different Collides in the Game. So i can direct him towards them.
I have kind of working code, but it has few bugs, i will describe below it
float sign;
float angle;
Vector3 targetDir;
Vector3 forwardDir;
Vector3 referenceRight;
float finalAngle;
Transform target;
void Start ()
{
target = GameObject.Find("Cube").transform;
}
void Update () {
targetDir = target.position - transform.position;
forwardDir = transform.forward;
angle = Vector3.Angle(targetDir, forwardDir);
referenceRight = Vector3.Cross(Vector3.down, forwardDir);
sign = Mathf.Sign(Vector3.Dot(targetDir, referenceRight));
finalAngle = sign * angle;
if (finalAngle < 180) { finalAngle = finalAngle + 180; }
else if (finalAngle > 180) { finalAngle = finalAngle - 180; }
Debug.Log(finalAngle);
}
This code is attached to the first person Player and i have tested it with Small and Big Colliders, Cubes and so on. And it works just fine, except for one bug.
BUG:
If i am standing close to the collider or the Cube or what ever is my target for degree calculation, the degree will jump between let's say 160-180.
If i go even closer, it will jump between 150-190!
The closer i am to the target, the more degrees are jumped over in the front !!!
I would really appreciate any solution. I thought about making a very small object in the collider towards it should point, but it did not help. I decreased the body of the first person character and made him very thin, did not help either ...
thank you very much in advance :)
Answer by derPuppeteer · Jun 21, 2015 at 07:10 PM
Hi, I think your problem is that you are comparing the angle between 2 3d Vectors. This should do the trick:
targetDir = target.position - transform.position;
forwardDir = transform.forward;
//new stuff
targetDir.y = fowardDir.y;
//end of new stuff
angle = Vector3.Angle(targetDir, forwardDir);