Plenty of threads on this and I’ve tried all their solutions but none of them work for me for one reason, and I’m sure it’s something so simple but I can’t figure it out.
My space shooter game uses the X and Z axis, where Z would be ‘up and down’ the screen. I tried to pass the Z value as the Y value…
// target is a Transform reference obviously
void UpdatePos()
{
Vector3 temp = new Vector3(target.position.x, -target.position.z, target.position.y);
getPixelPos = Camera.main.WorldToScreenPoint(temp);
gameObject.transform.position = Camera.main.ScreenToViewportPoint(getPixelPos);
}
And it works…kinda. I placed UpdatePos() in OnGUI but it renders on screen, but not directly over the target object. Also, it’s X screen movement is slower than its Y screen movement. How do I get the GUI object to hover directly over the target?
Ok I’m still working on this and I’ve added an offset and that’s helped the Y screen position, but the X position doesn’t keep up with the object when it moves. How can I fix this?
void UpdatePos()
{
// Offset is a value that can be changed in the inspector
Vector3 temp = new Vector3(target.transform.position.x, -target.transform.position.z, target.transform.position.y) + offset;
getPixelPos = Camera.main.WorldToViewportPoint(temp);
gameObject.transform.position = getPixelPos;
}
@eses
Thanks for showing me that thread, and thanks for reading this one. No I didn’t read your thread; Thanks to your response though, I learned about RectTransformUtility.ScreenPointToLocalPointInRectangle. I had come across this before but didn’t quite understand how to use it. I already had most of this work done, save for that piece of code, so I added into my file to test it out and now the GUI object doesn’t move at all. I’ve tried using it with an Image and a Text Object, still no movement at all.
Here’s my code if you care to look at it.
using UnityEngine;
using System.Collections;
public class FollowScreenTarget : MonoBehaviour
{
// This script will make a GUITexture follow a transform.
[SerializeField]
GameObject target;
Vector3 getPixelPos;
[SerializeField]
Vector3 offset;
[SerializeField]
Canvas canvas;
void UpdatePos()
{
Vector3 temp = new Vector3(target.transform.position.x, -target.transform.position.z, target.transform.position.y) + offset;
getPixelPos = Camera.main.WorldToScreenPoint(temp);
Vector2 canvasPos;
//EDIT: Added Camera.main because I'm not using Screen Space: Overlay
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.GetComponent<RectTransform>(), getPixelPos, Camera.main, out canvasPos);
gameObject.transform.localPosition = canvasPos;
}
void OnGUI()
{
UpdatePos();
}
}