- Home /
GUI.DrawTexture isn't centred. Help?
I've been trying to fix this issue for a while, but for some reason can't find an answer. In my game, I have a speed boost bar that I would like centred at the top of the screen. I have been using the following script:
var boostPercent : float;
var xPos : float = (Screen.width/2);
var yPos : float = 30;
var backgroundWidthBoost : float = Screen.width/5;
var boostWidth : float;
var height : float = backgroundWidthBoost/15;
var boostRemainingBehindTexture : Texture;
var boostRemainingTexture : Texture;
function OnGUI()
{
boostPercent = GameObject.Find("Suber").GetComponent(SubControl).boostTimer / GameObject.Find("Suber").GetComponent(SubControl).boostTime;
boostWidth = (boostPercent * backgroundWidthBoost * -1) + backgroundWidthBoost;
//Draws a rectangle of x,y position, rec width and height, and wrapped in a specified texture
GUI.DrawTexture(Rect(xPos,yPos,backgroundWidthBoost,height), boostRemainingBehindTexture, ScaleMode.StretchToFill, true, 1.0f);
GUI.DrawTexture(Rect(xPos,yPos,boostWidth,height), boostRemainingTexture, ScaleMode.StretchToFill, true, 1.0f);
}
For some reason, even though I specify the x position as 0.5 * Screen.width, the bar shows up way in the left hand corner (see image below). Any insight would be appreciated. Thanks!
Answer by robertbu · Jul 26, 2014 at 10:31 PM
First, a Rect is (x, y, dx, dy), so the x and y are the upper left corner of what you need to display, so to fix you need to subtract 1/2 of the width (dx) from x to move it back. Second, the way you are calculating xPos will happen only once when the script is attached to a game object and use whatever width you have for the screen in the editor. You need to move these calculations into the Start() function or even into OnGUI() if there the device you are targeting can change screen resolution (i.e. be rotated). And since these are calculated values and not set in the inspector, make them private:
private var xPos : float;
One way I often do these calculations is to create a rect of the right size with a position of (0,0):
var rect : Rect = Rect(0,0,someWidth, someHeight);
Then I can place the center of the rect at some specific position by:
rect.center = new Vector2(Screen.width/2, 40);
Awesome! Putting xPos into OnGUI() solved everything
Your answer
Follow this Question
Related Questions
Doubt with GUILayout 0 Answers
Fading an image drawn with GUI.DrawTexture 1 Answer
texCoords rect for GUI.DrawTextureWithTexCoords 3 Answers
Scale Car Speedometer with Screen Size (made by Andeeee) 1 Answer
GUI Rotation and Depth problem 1 Answer