So I have this script here that handles the firing of a weapon using raycasts and I’m trying to have it use a Line Renderer directly forward from the facing of the gun object. Initially I used hitInfo.point as the 2nd point for the line renderer but as there is no collision with the sky the line will not render there. After reading through other answers I determined that transform.TransformDirection(Vector3.forward) should project the line forward but when I run my game the line is always rendered to a fixed point despite which direction my player is facing ( and hence the gun’s facing direction). If anyone could point out my mistake here, it would be much appreciated.
public class RaycastMachineGun : MonoBehaviour {
float mCooldown = -0.1f;
float mFireRate = 0.1f;
int mGunAmmo = 0;
int mGunMaxAmmo = 500;
int mGunDamage = 10;
LineRenderer mGun;
float mGunCountDown = 0.125f;
float mCurrentCountDown = 0.0f;
void Start () {
mGun = GetComponent<LineRenderer>();
mGun.enabled = false;
mGun.SetVertexCount (2);
mGun.SetWidth (0.01f, 0.01f);
mGun.SetColors (Color.yellow, Color.yellow);
mGunAmmo = mGunMaxAmmo;
}
void Update () {
if(Input.GetButton("Fire1") && Time.time > mCooldown && mGunAmmo > 0)
{
mGunAmmo--;
RaycastHit hitInfo;
Vector3 direction = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, direction, out hitInfo))
{
if(hitInfo.transform.tag != "Player")
{
Health enemyHealth = hitInfo.transform.GetComponent<Health>();
if (enemyHealth!= null)
{
enemyHealth.mDamage(mGunDamage);
}
}
mGun.enabled = true;
mGun.SetPosition(0, transform.position);
mGun.SetPosition(1, direction);
}
mCooldown = Time.time + mFireRate;
}
mCurrentCountDown += Time.deltaTime;
if (mCurrentCountDown >= mGunCountDown)
{
mGun.enabled = false;
mCurrentCountDown = 0.0f;
}
}
void OnGUI(){
GUI.Label (new Rect (5, Screen.height - 45, 100, 100), "Ammo: " + mGunAmmo.ToString () + " / " + mGunMaxAmmo.ToString ());
}
}
Also as this is my first question on here, I’m not entirely sure I formatted everything properly, if someone could also point me to where to do that, thanks in advance.