Hi,I need to create a GUI.Box to the exact position and size of a sprite(square shape) and this no matter what the screen size/height is.
The sprite is 71*71 and the pixel to unit is set to 71.
I try this to retrieve the pixel position of the sprite but it don’t work like intended,it miss some math calculation which I have no clue of.
float ConvertUnitXToPixel(float unit)
{
float middle = Screen.width / 2f; //should be unit 0 I guess
float pixel = (unit * 71f);
return middle + pixel;
}
Thx in advance.
Assuming an orthographic camera an no rotation of the sprite, the following script when attached to sprite will place a GUI.Box over the sprite…even if the sprite is moving.
using UnityEngine;
using System.Collections;
public class BoxSprite : MonoBehaviour {
private Rect rect;
void Start() {
Sprite sprt = GetComponent<SpriteRenderer>().sprite;
var worldToPixels = ((Screen.height / 2.0f) / Camera.main.orthographicSize);
rect = new Rect(0,0,sprt.bounds.size.x * worldToPixels, sprt.bounds.size.y * worldToPixels);
}
void OnGUI() {
Vector3 temp = Camera.main.WorldToScreenPoint (transform.position);
temp.y = Screen.height - temp.y;
rect.center = temp;
GUI.Box (rect, "");
}
}