- Home /
Question by
ChazAshley1 · Jun 11, 2014 at 02:37 PM ·
guilabelworldtoscreenpoint
Wrong WorldToScreenPoint converting (not inverted y)
Hey. I have GameObject under character head and want to see character's nickname in this position. Here my code
using System;
using SCdll.NSServer;
using SCdll.NSServer.ServerInterface;
using UnityEngine;
using System.Collections;
public class ClientControl : MonoBehaviour
{
public CharInfo newData, lastData, info;
private Animator animator;
public float speed = 1;
private Transform myTransform;
private CharacterController controller;
private Vector3 velocity, pointPos;
public float time;
public ushort messageID = 0;
public int UserID;
private GUIStyle style;
private Transform nickPoint;
private Vector3 screen;
private Vector2 nickSize;
private float distance;
private float multiplier;
private float x;
private float y;
private Vector3 viewPortPos;
private Transform mesh;
// Use this for initialization
private void Start()
{
mesh = transform.FindChild("mesh");
animator = transform.FindChild("mesh").GetComponent<Animator>();
myTransform = transform;
velocity = Vector3.zero;
controller = transform.GetComponent<CharacterController>();
style = new GUIStyle();
style.alignment = TextAnchor.LowerCenter;
style.normal.textColor = Color.black;
style.fontSize = 19;
style.fontStyle = FontStyle.Bold;
nickPoint = transform.FindChild("nick");
screen = Camera.main.ViewportToScreenPoint(Camera.main.WorldToViewportPoint(nickPoint.transform.position));
nickSize = style.CalcSize(new GUIContent(TempStorage.nickname));
x = -11/90f;
y = 182/9f;
}
// Update is called once per frame
void Update()
{
distance = Vector3.Distance(myTransform.position, Camera.main.transform.position);
if (distance <= 10)
{
style.fontSize = 19;
}
else if (distance >= 100)
{
style.fontSize = 8;
}
else
{
style.fontSize = (int) Math.Floor(distance*x + y);
}
// Debug.Log("Font size is: " + style.fontSize + " Distance is: " + distance);
}
void OnGUI()
{
if (info != null)
{
viewPortPos = Camera.main.WorldToViewportPoint(nickPoint.transform.position);
// Debug.Log("viewPortPos: " + viewPortPos);
if (viewPortPos.x >= 0 && viewPortPos.x <= 1 && viewPortPos.y >= 0 && viewPortPos.y <= 1 && viewPortPos.z>0
&& !Physics.Linecast(nickPoint.transform.position,Camera.main.transform.position) && distance<=100)
{
screen = Camera.main.WorldToScreenPoint(nickPoint.transform.position);
GUI.Label(new Rect(screen.x - 25, Screen.height-screen.y, 50, 25), info.NickName,style);
}
}
}
}
What is my problem? When the character goes far away then nickname goes down. I don't know why, really, no idea... Maybe someone knows why it happens? p.s. here is my video proof, pink sphere - point where nickname must be VIDEO
Comment
@Andres Fernandez has spotted the likely right issue. Your text is top anchored. You are going to need to get the text height and move the anchor to the bottom of the text.
PLEASE WATCH THE CODE
style.alignment = TextAnchor.LowerCenter;