这里在做的是一个player受伤闪烁的效果,用的是standard shader的自发光参数;
首先确定需要的变量:
[Header("Hurt Flash---")]public float hurtFlashSpeed = 1f;public float emissionFloor = 0.3f;public float emissionCeil = 1f;public float hurtMaxDuration = 1f;private float timeSinceLastHurt;private bool isInHurtState;
然后在OnEnable中获取材质,以及初始化:
// hurt flash isInHurtState = false;timeSinceLastHurt = 0;playerMat = GetComponent<Renderer>().material;playerMat.EnableKeyword("_EMISSION");playerMat.SetColor("_EmissionColor", Color.clear);
之后在update中,进行闪烁:
// hurt flash --------------------------------------------- hurt flash effectif (isInHurtState){timeSinceLastHurt += Time.deltaTime;if (timeSinceLastHurt > hurtMaxDuration){Debug.Log("Recover!");timeSinceLastHurt = 0;isInHurtState = false;// set to normal state//playerMat.EnableKeyword("_EMISSION");playerMat.SetColor("_EmissionColor", Color.clear);return;}float emission = emissionFloor + Mathf.PingPong(Time.time * hurtFlashSpeed, emissionCeil - emissionFloor);Color baseColor = Color.yellow;Color finalColor = baseColor * Mathf.LinearToGammaSpace(emission); // better transition for human eyes//playerMat.EnableKeyword("_EMISSION");playerMat.SetColor("_EmissionColor", finalColor);}
注意:Mathf.LinearToGammaSpace更符合人眼观察的过度;
参考链接:
/questions/914923/standard-shader-emission-control-via-script.html
/Manual/MaterialsAccessingViaScript.html