- Home /
The question is answered, right answer was accepted
Raycast shooting
I have a weapon firing using raycast, when i click the mouse it fires, but the muzzle flash only appears when im pointing it at a target.
any suggestions as to why this happens?
the shoot section of the code
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log (hit.transform.name);
Instantiate (flash, flashSpawn.position, flashSpawn.rotation); //addition
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
}
Answer by Favouriteless · Nov 12, 2018 at 01:26 PM
When using a Raycast in an if statement it only evaluates to true if the Raycast has hit something. You need to add the muzzle flash outside the if statement because it is only executed when the Raycast is hitting a collider, not when the Raycast is fired. This script should work for you, I have just moved your flash instantiate outside the if statement:
void Shoot()
{
Instantiate (flash, flashSpawn.position, flashSpawn.rotation);
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log (hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
Follow this Question
Related Questions
Trouble with Raycast shooting 1 Answer
Raycast shooting in the middle of the screen 1 Answer
How do I make my raycast shooting script full auto 1 Answer
Shotgun raycast 1 Answer