Hi there!
I’ve got a compass that’s slightly rotated on the Z axis. (I’m using a game object for a GUI instead of a GUItexture, personal choice).
Now I’d love to get the needle of said compass (separated as it’s own mesh) to always look at a certain object far away. I’ve tried the standard lookat, and obviously the needle rotates oddly on all the axis. I’ve also tried to lock it on one axis, but it doesn’t only not work, I suspect it’ll lock it flat on an axis, which won’t do because my compass isn’t flat.
Here’s my beautiful non working code.
using UnityEngine;
using System.Collections;
public class compass : MonoBehaviour {
public GameObject target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.LookAt(Vector3(target.x, transform.position.y, target.z));
}
}
Any help in C# would be greatly appreciated, thank you!
I’m going to assume your compass is at some arbitrary angle aligned to the axes. If so, the solution is to project your target point onto a plane passing through the compass at the angle of the compass. So go out and get the Math3d script from the Unity Wiki, and add it to your project.
The method you want from the script is ProjetPointOnPlane(). Assuming your compass is constructed so that the face is transform.up, you code will be:
void Update() {
Vector3 v3 = ProjectPointOnPlane(compass.transform.up, compass.transform.position, target.transform.position;
transform.LooAt(v3);
}
Actually you should be able to use the position and rotation of the needle as well if the angle of the compass does not change during the game:
void Update() {
Vector3 v3 = ProjectPointOnPlane(transform.up,transform.position, target.transform.position;
transform.LooAt(v3);
}
P.S. The code you posted would have generated a syntax error since target is a game object and game object don’t have x, y, and z, components. It should be ‘target.transform.position.z’. Or you can make the code (original or recommended change) more efficient by making target a Transform.