Hey everyone!
Along with most if us, i’m currently experimenting with the new ui system. i got stuck at the point converting my enemy indicator script (based on the original, see code below) to the new ui system. The script simply shows enemy icons on the side of the screen pointing to enemys that are not displayed by the players camera. it currently uses GUIText components for that.
i tried to set the camera canvas to worldspace but since the RectTransforms values “are always relative” to something (wich in general is very awesome), i cant get my head around how to convert values right.
I’m sure there is a simple work around for this to directly feed the new UI element with converted positions.
any advice is welcome ![]()
eric5h5’s ObjectLabel.cs :
http://wiki.unity3d.com/index.php?title=ObjectLabel
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (GUIText))]
public class ObjectLabel : MonoBehaviour {
public Transform target; // Object that this label should follow
public Vector3 offset = Vector3.up; // Units in world space to offset; 1 unit above object by default
public bool clampToScreen = false; // If true, label will be visible even if object is off screen
public float clampBorderSize = 0.05f; // How much viewport space to leave at the borders when a label is being clamped
public bool useMainCamera = true; // Use the camera tagged MainCamera
public Camera cameraToUse ; // Only use this if useMainCamera is false
Camera cam ;
Transform thisTransform;
Transform camTransform;
void Start ()
{
thisTransform = transform;
if (useMainCamera)
cam = Camera.main;
else
cam = cameraToUse;
camTransform = cam.transform;
}
void Update()
{
if (clampToScreen)
{
Vector3 relativePosition = camTransform.InverseTransformPoint(target.position);
relativePosition.z = Mathf.Max(relativePosition.z, 1.0f);
thisTransform.position = cam.WorldToViewportPoint(camTransform.TransformPoint(relativePosition + offset));
thisTransform.position = new Vector3(Mathf.Clamp(thisTransform.position.x, clampBorderSize, 1.0f - clampBorderSize),
Mathf.Clamp(thisTransform.position.y, clampBorderSize, 1.0f - clampBorderSize),
thisTransform.position.z);
}
else
{
thisTransform.position = cam.WorldToViewportPoint(target.position + offset);
}
}
}
//edit: language fixes