- Home /
How to truncate sprite without changing the scale of the sprite?
For now, I use transform.localScale to design a HP bar that will keep decreasing HP when player get hit but because of localScale issue I get the undesired result as image below. I dun want tat portion also changing.
You will ask why dun just put a complete rectangle to do that but the UI layout is semi-transparent as image below. So, I need a way to truncate the sprite without modifying the scale of sprite.
My desired output is decrease the HP bar without changing the frame layout of the HP UI as the sample image below.
Here is my code for modifying scale of the sprite:
using UnityEngine;
using System.Collections;
public class HPBar : MonoBehaviour
{
public float hp = 1800;
public float damage = 510;
float totalhp;
float healthPercent = 100;
SpriteRenderer hpBar;
Vector3 hpScale;
void Start()
{
hpBar = GetComponent<SpriteRenderer>();
hpScale = hpBar.transform.localScale;
totalhp = hp;
}
void Update()
{
// Mouse left click
if (Input.GetMouseButtonDown(0))
{
hp -= damage;
if (hp > 0)
healthPercent = hp / totalhp;
else
healthPercent = 0;
hpBar.transform.localScale = new Vector3(hpScale.x * healthPercent, 1, 1);
}
}
}
Use a different sprite bar( of the size of the bar below the main hp bar) object and super impose over the $$anonymous$$i bar sprite .. And then use a seperate code to manipulate the superimposed sprite.. Red
Not very understand wat u say. Can u explain in details? Thanks. Btw my desired output is decrease the HP bar without changing the frame layout of the HP UI.
Answer by Itaros · Oct 22, 2014 at 07:28 AM
Write a custom shader capable of truncating alpha by mask and supplied scaling factor(as float)
Why I get "$$anonymous$$aterial uses fixed function shader. It is not compatible with SpriteRenderer" error?
Shader "Custom/$$anonymous$$askTest" {
Properties
{
_$$anonymous$$ainTex ("Base (RGB) Alpha (A)", 2D) = "white" {}
_Cutoff ("Base Alpha cutoff", Range (0,.9)) = .5
}
SubShader {
Tags {"Queue" = "Transparent"}
Offset 0, -1
Color$$anonymous$$ask 0
ZWrite On
Pass
{
AlphaTest Greater [_Cutoff]
SetTexture [_$$anonymous$$ainTex] {
combine texture * primary, texture
}
}
}
}
You need proper vertex and fragment programs http://docs.unity3d.com/$$anonymous$$anual/SL-VertexFragmentShaderExamples.html
Your answer
Follow this Question
Related Questions
Why is my sprite not the original resolution? 2 Answers
Sprite Renderer Not Changing Sprite via Script 1 Answer
Change Spritesheet Programatically 1 Answer
Gui Box - Texture - Spritesheet 0 Answers