- Home /
Raycast not firing
new to this, followed this video however I created my own gun in Blender. I followed everything he did but my raycast will not fire, and I'm getting no errors. also, earlier I was getting errors with Rayviewer so I just decided to delete it, can anyone help me?
using UnityEngine; using System.Collections;
public class RaycastGun : MonoBehaviour {
public int gunDamage = 1;
public float fireRate = .25f;
public float weaponRange = 15f;
public float hitForce = 100f;
public Transform gunEnd;
private Camera fpsCam;
private WaitForSeconds shotDuration = new WaitForSeconds(.07f);
private AudioSource gunAudio;
private LineRenderer laserLine;
private float nextFire;
// Use this for initialization
void Start () {
laserLine = GetComponent<LineRenderer> ();
gunAudio = GetComponent<AudioSource> ();
fpsCam = GetComponentInParent<Camera> ();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
StartCoroutine (ShotEffect());
Vector3 rayOrigin = fpsCam.ViewportToWorldPoint (new Vector3 (0.5f, 0.5f, 0));
RaycastHit hit;
laserLine.SetPosition(0, gunEnd.position);
if (Physics.Raycast(rayOrigin,fpsCam.transform.forward, out hit, weaponRange))
{
laserLine.SetPosition(1, hit.point);
}
else
{
laserLine.SetPosition(1, rayOrigin + (fpsCam.transform.forward * weaponRange));
}
}
}
private IEnumerator ShotEffect ()
{
gunAudio.Play ();
laserLine.enabled = true;
yield return shotDuration;
laserLine.enabled = false;
}
}
Better attach your project files, your code is fine.
I suggest you check that the point you're firing the raycast from is not within a collider. If it is it'll insta-hit that collider and that will, of course, not yield the expected results.
Also there are multiple ways to make the raycast ignore said collider. Like specifying a Layermask to ignore certain layers. See here: http://answers.unity3d.com/questions/409360/raycasthit-behind-object.html It's basically the situation I have described and a solution. If that suits your use case.