I’m attempting to make an m4a1 fire via RayCast. I read through the scripting reference and understand it for the most part however I’ve run in to a problem. The script I am using is as follows:
var Range : float = 1000;
var Force : float = 200;
var Clips : int = 20;
var BulletsInClip : int = 60;
var ReloadTime : float = 2.2;
var BulletsLeft : int = 0;
var ShootDelay : float = 0;
var ShootCooldown : float = 0.2;
public var audioShot : AudioClip;
public var audioReload : AudioClip;
function Start()
{
BulletsLeft = BulletsInClip;
}
function Update ()
{
if(ShootDelay > 0)
{
ShootDelay -= Time.deltaTime;
}
else
{
ShootDelay = 0;
}
if(Input.GetButton("Fire1"))
{
if(ShootDelay == 0 && BulletsLeft > 0)
{
PlayShot();
BulletsLeft--;
CastRay();
ShootDelay = ShootCooldown;
}
if (BulletsLeft == 0 && Clips > 0)
{
ShootDelay = ReloadTime;
BulletsLeft = 0;
Reload();
}
}
}
function CastRay()
{
var Hit : RaycastHit;
var DirectionRay = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, DirectionRay * Range, Color.magenta);
if(Physics.Raycast(transform.position , DirectionRay , Hit, Range ))
{
if(Hit.rigidbody)
{
Hit.rigidbody.AddForceAtPosition(DirectionRay * Force , Hit.point);
}
}
}
function Reload()
{
yield WaitForSeconds(ReloadTime);
PlayReload();
BulletsLeft = BulletsInClip;
Clips--;
}
function PlayShot()
{
audio.PlayOneShot(audioShot);
}
function PlayReload()
{
audio.PlayOneShot(audioReload);
}
However when the gun runs out of ammo, it reloads but continues firing. This causes the gun to continue using up a spare clip until it has a negative amount of clips remaining, which will then stop it from reloading any more.
Any insight you guys can provide would be much appreciated.
Thanks in advance.