Question by
ridley1224 · Jan 11, 2016 at 04:27 PM ·
indicator
Player Indicator Label Position not Updating Correctly
My player indicator works correctly if the camera is looking straight ahead, but the label's position becomes inaccurate when the first person controller looks up or down. How do I fix the inaccurate position?
void OnGUI() {
indictor3 ();
}
void indictor3 () {
for (int i = 0; i < enemyList.Length; i++) {
GameObject player = (GameObject)enemyList[i];
Vector3 playerCoords = player.transform.position;
Vector3 screenCords = fpc.WorldToScreenPoint (playerCoords); //fpc is my first person camera
Vector3 worldToViewPos = fpc.WorldToViewportPoint (playerCoords);
if (worldToViewPos.z < 0) {
//print ("Object is behind the camera: " + worldToViewPos);
return;
}
GUI.Label (new Rect (screenCords.x, screenCords.y, 40, 20), player.name);
}
}
Comment
Best Answer
Answer by ridley1224 · Jan 11, 2016 at 07:41 PM
Solved it myself. I added an offset to update the label's position to the location of the enemy on screen and set a static Y position at the top and bottom for when the enemy is positioned above or below the screen.
for (int i = 0; i < enemyList.Length; i++) {
GameObject player = (GameObject)enemyList[i];
Vector3 playerCoords = player.transform.position;
Vector3 screenCords = fpc.WorldToScreenPoint (playerCoords);
Vector3 worldToViewPos = fpc.WorldToViewportPoint (playerCoords);
float offset = screenCords.y - Screen.height/2;
if (worldToViewPos.z < 0)
{
return;
}
if(worldToViewPos.y >= 1)
{
GUI.Label (new Rect (screenCords.x, 20, 60, 20), player.name);
}
else if(worldToViewPos.y <= 0)
{
GUI.Label (new Rect (screenCords.x, Screen.height - 20, 60, 20), player.name);
}
else
{
GUI.Label (new Rect (screenCords.x, screenCords.y - (offset * 2), 60, 20), player.name);
}
}