1
votes

I have one imageTarget, I track that imageTarget with ARCamera, I want to find angle X of imageTarget relative to ARCamera(mobile device), because I need to move my object(imageTarget) towards the camera. I am using Vuforia in Unity. If possible please provide me code sample, as I am new in Unity, don't know much. I am sharing you my effort here. I am using this code for calculating angle, I think it is not correct. Please review it. Please help me.

Transform dummy = new GameObject("Dummy").transform;
dummy.SetParent(trackableEventHandler.transform);
dummy.LookAt(Camera.main.transform, trackableEventHandler.transform.up);
float angle = Mathf.Atan2(dummy.forward.z, dummy.forward.x) - Mathf.Atan2(trackableEventHandler.transform.forward.z, trackableEventHandler.transform.forward.x);
angle *= Mathf.Rad2Deg;
text.text = angle.ToString();
1

1 Answers

0
votes

Try this

Transform dummy = new GameObject("Dummy").transform;
dummy.SetParent(trackableEventHandler.transform);
dummy.LookAt(Camera.main.transform, trackableEventHandler.transform.up);
float angle = Vector3.Angle(Camera.main.transform.forward, dummy.position - Camera.main.transform.position);
text.text = angle.ToString();

Edit: For signed angles, use this instead

float angle = Vector3.SignedAngle(Camera.main.transform.forward, dummy.position - Camera.main.transform.position, Vector3.up);

For 2D signed angles, use this instead

float angle = Vector2.SignedAngle(Vector2(Camera.main.transform.forward.x, Camera.main.transform.forward.z), Vector2(dummy.positionx.x - Camera.main.transform.position.x, dummy.positionx.z - Camera.main.transform.position.z));