Mathf.Clamp() Not working, one corner only.
The code works, this is used for an OffScreen enemy indicator (Location of enemy), but an issue is arising on play. The arrow used will only show on the bottom left corner of the screen, I can see that they are moving but only in one corner, not the whole screen, I've looked through this all morning and I cannot find what went wrong if anyone can point me in the right direction I would be very grateful. EDIT: I just tested a few more times and noticed, when I look at the object the arrow does not go away it stays on screen, I believe this is something to do with area set?
public Texture2D icon; //The icon. Preferably an arrow pointing upwards.
public float iconSize = 50f;
[HideInInspector]
public GUIStyle arrow; //GUIStyle to make the box around the icon invisible. Public so that everything has the default stats.
Vector2 indRange;
float scaleRes = Screen.width/200; //The width of the screen divided by 500. Will make the GUI automatically
//scale with varying resolutions.
Camera cam;
public bool visible = false; //Whether or not the object is visible in the camera.
void Start () {
visible = GetComponent<SpriteRenderer> ().isVisible;
cam = Camera.main; //Don't use Camera.main in a looping method, its very slow, as Camera.main actually
//does a GameObject.Find for an object tagged with MainCamera.
indRange.x = Screen.width - (Screen.width / 6);
indRange.y = Screen.height - (Screen.height / 7);
indRange /= 2f;
arrow.normal.textColor = new Vector4 (0, 0, 0, 0); //Makes the box around the icon invisible.
}
void OnGUI () {
if (visible) {
Vector3 dir = transform.position - cam.transform.position;
dir = Vector3.Normalize (dir);
dir.y *= -1f;
Vector2 indPos = new Vector2 (indRange.x * dir.x, indRange.y * dir.y);
indPos = new Vector2 ((Screen.width / 2) + indPos.x,
(Screen.height / 2) + indPos.y);
Vector3 pdir = transform.position - cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y,
transform.position.z));
pdir = Vector3.Normalize(pdir);
float angle = Mathf.Atan2(pdir.x, pdir.y) * Mathf.Rad2Deg;
GUIUtility.RotateAroundPivot(angle, indPos); //Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before.
GUI.Box (new Rect (indPos.x, indPos.y, scaleRes * iconSize, scaleRes * iconSize), icon,arrow);
GUIUtility.RotateAroundPivot(0, indPos); //Rotates GUI back to the default so that GUI drawn after is not rotated.
}
}
public void OnBecameInvisible() {
visible = false;
}
//Turns off the indicator if object is onscreen.
public void OnBecameVisible() {
visible = true;
}
Your answer
Follow this Question
Related Questions
Moving GUI Label through key board? 1 Answer
Vector2.lerp dashing problem 0 Answers
Moved GameObject under Canvas (Parent), transform.position vector coordinates mismatch 0 Answers
Turn a vector3 relative to a look direction 1 Answer
Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers