Skip to content

Instantly share code, notes, and snippets.

@anselm
Created October 7, 2014 23:22
Show Gist options
  • Save anselm/51315a8c866acc175cf2 to your computer and use it in GitHub Desktop.
Save anselm/51315a8c866acc175cf2 to your computer and use it in GitHub Desktop.
An example of having a 2d arrow on the screen follow a 3d object in the world as a kind of radar hint about where that object is (for Unity3D).
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ArrowScript : MonoBehaviour {
public GameObject lookat;
public Camera camera;
public const float EDGE = 0.3f;
public const float DIST = 100;
public Color color = new Color(1,1,1,1);
void Start () {
}
void Update () {
Vector3 viewpos = camera.transform.InverseTransformPoint( lookat.transform.position );
viewpos.Normalize();
// get a position from -0.5 to 0.5 in xy space - which actually doesn't do what it claims sigh.
//Vector3 viewpos = camera.WorldToViewportPoint( lookat.transform.position );
//viewpos.x = (viewpos.x - 0.5f);
//viewpos.y = (viewpos.y - 0.5f);
// fade if not needed
if(((viewpos.x >-EDGE && viewpos.x < EDGE) && (viewpos.y >-EDGE && viewpos.y < EDGE)) && viewpos.z > 0) {
color.a = color.a > 0.0f ? color.a - 0.01f : 0.0f;
renderer.sharedMaterial.color = color;
} else {
color.a = color.a < 0.5f ? color.a + 0.01f : 0.5f;
renderer.sharedMaterial.color = color;
}
// rotate the arrow around lookat axis
float angle = Mathf.Atan2(viewpos.y, viewpos.x) * Mathf.Rad2Deg + 90;
transform.localRotation = Quaternion.AngleAxis(angle, Vector3.forward) * Quaternion.Euler (270,0,0);
// constrain the arrow to the screen; it should fade away when on screen; we allow it to come off the edge in that case
if(viewpos.x > EDGE ) viewpos.x = EDGE;
if(viewpos.x <-EDGE ) viewpos.x = -EDGE;
if(viewpos.y > EDGE ) viewpos.y = EDGE;
if(viewpos.y <-EDGE ) viewpos.y = -EDGE;
// place the arrow
transform.localPosition = new Vector3( viewpos.x * DIST, viewpos.y * DIST, DIST/2.0f );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment