I am creating a first person shooter script. In order to get the bullet to travel straight at the cross-hair, I calculate the ray hit and shoot the bullet in that direction. The problem is if there is nothing within the range, it won't shoot at all, which isn't how a gun works. The script I have right now checks if there was a hit, and if there wasn't, it defaults to shooting straight out of the gun. Like so:
void Update () {
if(Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(crossHair.transform.position);
GameObject bullet = Instantiate(bullet_prefab, bullet_spawn.transform.position, bullet_spawn.transform.rotation) as GameObject;
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
if (Physics.Raycast(ray, out rayHit, 100000.0f))
{
Debug.DrawLine(bullet_spawn.transform.position, rayHit.point, Color.red);
bulletRigidbody.AddForce((rayHit.point - bullet_spawn.transform.position).normalized * bulletImpulse, ForceMode.Impulse);
}
else
{
bulletRigidbody.AddForce(bullet_spawn.transform.position * bulletImpulse, ForceMode.Impulse);
}
EmitShotParticles();
}
}
The problem with this is that it seems it would be unfair. The player can have the cross-hair directly beside a target and still hit them. I need a way to constantly shoot at a direct ray to the cross-hair from the gun, rather than two separate calculations for the bullets path.