- Home /
Draw texture the same size of a sprite
I'm working on some enemies for my game and i'll draw a health bar over then when they've taken some damage.
Here's what i got (this script is linked to the sprite):
 Vector3 position = Camera.main.WorldToScreenPoint(new Vector3(transform.position.x, transform.position.y, 0));
 Vector3 size = Camera.main.WorldToScreenPoint (transform.renderer.bounds.size);
 GUI.DrawTexture(new Rect(position.x,Screen.height-position.y,size.x,size.y), hpBarDetail, ScaleMode.StretchToFill);
The position is almost fine, but the size is messed up. The sprite is small but the texture size is almost the screen size.
How do i draw a texture the same size a sprite is being drawn on the screen?
Answer by solci · May 03, 2014 at 02:44 PM
I found the answer. I made some conversions and got the size i wanted (The height i fixed because it was weird scaling with object's height)
 float vertExtend = Camera.main.orthographicSize;
 float horzExtent = vertExtend * Screen.width / Screen.height;
 float widthRatio = Screen.width / (horzExtent *2f);
 Vector3 size = transform.renderer.bounds.size;
 hpBarWidth = transform.renderer.bounds.size.x * widthRatio;
 hpBarHeight = Screen.height / 36;
 Vector3 position = Camera.main.WorldToScreenPoint(new Vector3(transform.position.x, transform.position.y, 0));
 Vector3 size = Camera.main.WorldToScreenPoint (transform.renderer.bounds.size);
 GUI.DrawTexture(new Rect(position.x,Screen.height-position.y,hpBarWidth ,hpBarHeight ), hpBarDetail, ScaleMode.StretchToFill);
Your answer
 
 
             Follow this Question
Related Questions
[Android] Screen Scaling?! 0 Answers
How to maintain high resolution custom background images for GUI elements on different screen sizes? 0 Answers
Help finding the right scale for an icon inside a backgorund sprite 1 Answer
GameObjects get cut of when screen changes 0 Answers
Standalone build with 3:2 aspect ratio 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                