- Home /
Scale GUI Texture From the Center.
Hi, I have a circle texture imported into unity for the crosshair. I have it become bigger every time you shoot. However, I don't know how to make it so that it scales from the center and not from the top-right corner. Also, if it was imported as an image, can I still change the color with GUI.backgroundColor? I am asking this because when I imported it it became lighter. Thanks!
var crosshairTexture: Texture2D;
var crosshairPosition: Rect;
var crosshairActive = true;
var playerWalkScript: PlayerMovementScript;
var gunScript: GunScript;
function Start()
{
playerWalkScript = GameObject.FindWithTag("Player").GetComponent(PlayerMovementScript);
}
function Update()
{
gunScript = playerWalkScript.currentGun.GetComponent(GunScript);
crosshairPosition = Rect(((Screen.width ) / 2), ((Screen.height ) / 2), crosshairTexture.width * gunScript.currentAccuracy * 3, crosshairTexture.height * gunScript.currentAccuracy * 3);
}
function OnGUI()
{
if(crosshairActive == true)
{
GUI.DrawTexture(crosshairPosition, crosshairTexture);
}
if (gunScript.ammoClip == 0)
{
GUI.backgroundColor = Color.red;
}
}
Do your gunScript.currentAccuracy updates per frame in the script?
Yes, but that's not the problem. It scales, just not in the correct way. It scales from the top left and not from the center, which is what I want.
Answer by robertbu · Apr 03, 2013 at 06:09 AM
One easy way to thing about this problem is that you want to "inflate" the rect while maintain the same center position. It means you want to offset the anchor by 1/2 of the increase in width and height, and you want to increase the width and height by the same amount. Say you want to increase the width by 100 pixels and the height by 80 pixels.
halfWidth = 100 / 2;
halfHeight = 80 / 2;
crosshairPosition.x -= halfWidth;
crosshairPosition.y += halfHeight;
crosshairPosition.width += halfWidth;
crosshairPosition.height += halfHeight;
The resulting rectangle will have the same center point but is now bigger.
Note you can roll these calculations into a single step rather than first calculating crosshairPosition and then inflating the rectangle, but this is a way to think about the problem.