- Home /
How to Create enemy flash effect on Raycast hit
Hi,
I have a question. I'm trying to set up an affect where an enemy flashes when hit. Think classic arcade brawlers like X Men, or NES titles like Castlevania:
My problem. I know how to code it when one object collides with another. I'm having trouble doing the same thing with a raycast hit, Which is what my current game is using. So my question, how do I create this effect when using a Raycast vs OnTrigger enter.
Here's my script. It is attached to the object taking a hit, in this case the enemy: (Raycast happens in a different script)
var materials = new Material[2];
function OnTriggerEnter ( otherobject : Collider)
{
if (otherobject.tag == "Player")
{
renderer.material = materials[1];
yield WaitForSeconds(.025);
renderer.material = materials[0];
}
}
Thanks in advance
Answer by Berenger · Jun 04, 2012 at 04:15 PM
On the player's script, when the ray hit something, check if the gameobject has the enemy script. If it does, call the following function from it :
function Flash()
{
renderer.material = materials[1];
yield WaitForSeconds(.025);
renderer.material = materials[0];
}
Answer by GutoThomas · Jun 04, 2012 at 04:18 PM
You can add a function in the script which would be hit, and when you get the raycast colliding with a object with this script you just call the function.
public function flashEffect () {
renderer.material = materials[1];
yield WaitForSeconds(.025);
renderer.material = materials[0];
}
I'll assume that the flashEffect function is assigned to a script who's called flashScript, just to exemplify.
Raycast launch:
var hit: RaycastHit;
var ray: Ray = GameObject.FindGameObjectWithTag("MainCamera").camera.ScreenPointToRay(Vector3(Screen.width/2, Screen.height/2, 0); // I'm using the center of the screen to detect the collision, as you can see
if(Physics.Raycast(ray, hit)) {
var fs: flashScript = hit.transform.GetComponent(flashScript);
if(fs != null) {
fs.flashEffect();
}
}