UI compass pointing to a 3D object
I have an arrow image sprite pointing up by default in the middle of the screen and I want it to rotate according to a target in 3D space in relation to the main camera.
My script is giving unexpected results:
using UnityEngine;
using System.Collections;
public class HudCompass : MonoBehaviour
{
public GameObject uiArrow;
private Camera _camera;
public Vector3 targetPosition;
void Start()
{
this._camera = Camera.main;
}
void Update()
{
Vector3 heading = transform.InverseTransformDirection(this._camera.transform.position - this.targetPosition);
float angle = Vector3.Angle(heading, this._camera.transform.forward);
uiArrow.transform.eulerAngles = new Vector3(0, 0, angle);
}
}
Could anybody point me in the right direction please? (pun intended)
Update: got it to work almost right
void Update()
{
Vector3 targetDir = targetPosition - this._camera.transform.position;
float angle = Vector3.Angle(targetDir, this._camera.transform.forward);
// Get normalized direction
float whichWay = Vector3.Cross(this._camera.transform.forward, targetDir).y;
if(whichWay > 0)
{
angle = -angle;
}
uiArrow.transform.eulerAngles = new Vector3(0, 0, angle);
}
The only problem is that the rotation "jumps" around where the angle is reversed. Does anyone have an idea why or a better solution?
Thanks
Try:
var target_pos_local = this._camera.transform.InverseTransformPoint(targetPosition);
var angle_target_h = $$anonymous$$athf.Atan2(target_pos_local.x, target_pos_local.z) * $$anonymous$$athf.Rad2Deg;
uiArrow.transform.eulerAngles = new Vector3(0, 0, angle_target_h);
Not sure that this will help, this is just another way to get horizontal angle with correct sign ins$$anonymous$$d of using cross and angle inverse.
This works way better than angle and cross indeed, very smooth. I only had to reverse the angle:
uiArrow.transform.eulerAngles = new Vector3(0, 0, -angle_target_h);
Thank you very much!
Your answer
Follow this Question
Related Questions
Clamping Between Two Different Ranges 1 Answer
Camera X Rotation Problems 0 Answers
Limit camera rotaion on x axis euler angles 1 Answer
Recognize when ever camera looks up and turns back down 0 Answers