- Home /
Straight Raycast Shooting
Can someone help me with my Raycast shooting. Now it shoots kind of randomly, and I want to it shoot exactly straight. Please help, I've tried everything.
var fireRate = 0.02;
var force = 10.0;
static var damage = 25;
var bulletsPerClip = 30;
static var clips = 3;
var range = 100;
static var bulletsLeft : int = 30;
private var hitParticles : ParticleEmitter;
private var nextFireTime = 0.0;
function Start () {
hitParticles = GetComponentInChildren(ParticleEmitter);
// We don't want to emit particles all the time, only when we hit something.
if (hitParticles)
hitParticles.emit = false;
}
function Update () {
if(Input.GetMouseButton(0))
{
Fire();
}
if (bulletsPerClip == 0)
{
Reload ();
}
if (Input.GetKeyDown ("r"))
Reload ();
}
function Fire () {
if (bulletsLeft == 0)
return;
if (bulletsPerClip == 0)
return;
// If there is more than one bullet between the last and this frame
// Reset the nextFireTime
if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;
// Keep firing until we used up the fire time
while( nextFireTime < Time.time && bulletsLeft != 0) {
FireOneShot();
nextFireTime += fireRate;
}
}
function FireOneShot () {
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
// Did we hit anything?
if (Physics.Raycast (transform.position, direction, hit, range)) {
// Apply a force to the rigidbody we hit
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
// Place the particle system for spawing out of place where we hit the surface!
// And spawn a couple of particles
if (hitParticles) {
hitParticles.transform.position = hit.point;
hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
hitParticles.Emit();
}
// Send a damage message to the hit object
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
bulletsLeft--;
// Register that we shot this frame,
// so that the LateUpdate function enabled the muzzleflash renderer for one frame
m_LastFrameShot = Time.frameCount;
enabled = true;
// Reload gun in reload Time
if (bulletsLeft == 0)
Reload();
}
function Reload(){
if (clips > 0) {
animation.Play("reload");
yield WaitForSeconds(1.25);
bulletsLeft = 30;
bulletsPerClip = 30;
clips--;
}
}
I don't see anything wrong with your code. It is shooting out the forward of the object it is attached to. To help you visualize what is going on, insert between lines 55 and 56:
Debug.DrawRay(transform.position, direction * range);
Turn Gizmos on by clicking on the Gizmos button in the upper right corner of the Game window.
Is the issue what object is hit by the raycast, or how the object moves when you do the AddForceAtPosition()?
That "fixed" it! Thank you but now my idle animation is messed up, ins$$anonymous$$d of the gun being on the right side of the camera every time idle animation is played the gun is on the left side.
I don't think you have the information here for someone to help you solve your animation problem.
Answer by citizen_rafiq · Oct 02, 2013 at 02:24 PM
/ attach this script with your gun and put an empty game object as a child of gun which work as spawn point of bullet
public class AutoFire : MonoBehaviour {
public float frequency = 10;
public float coneAngele = 1.0f;
public bool firing = false;
public float hitSoundVolume = 5f;
public GameObject muzzleFlash;
public AudioClip soundHit;
private float _lastFireTime = -1;
private RaycastHit _hitInfo;
private Quaternion _coneRandomRotation;
private Vector3 _force;
private GameObject _bullet;
private Transform _spawnPoint;
RaycastHit hitInfo;
void Start () {
if(muzzleFlash) muzzleFlash.active = false;
_force = new Vector3(0,0,0);
_bullet=Resources.Load("Prefabs/bullet", typeof(GameObject))as GameObject;
if(!_bullet){
Debug.LogError("keep bullet prefab in Resources/Prefabs/bullet");
}
foreach(Transform tr in transform){
if(tr){
_spawnPoint=tr;
}
}
}
// Update is called once per frame
void Update () {
if (firing) {
if (Time.time > _lastFireTime + 1 / frequency) {
//coneRandomRotation= Quaternion.Euler (Random.Range(-coneAngele, coneAngele), Random.Range(-coneAngele, coneAngele),0);
_coneRandomRotation = Quaternion.Euler(0, 0, 0);
GameObject go= Instantiate(_bullet,_spawnPoint.position,Quaternion.Euler(Vector3.zero)) as GameObject;
SimpleBulletOrMissile bulletOrMissile = go.GetComponent<SimpleBulletOrMissile>();
_lastFireTime = Time.time;
Physics.Raycast (go.transform.position, go.transform.up,out _hitInfo,Mathf.Infinity,-5);
if (_hitInfo.transform)
{
print(_hitInfo.transform.tag+"hitted");
Health targetHealth = _hitInfo.transform.GetComponent<Health>();
if (targetHealth)
{
//kill or health damage of target
}
if (_hitInfo.rigidbody)
{
//if want to apply force on enemy
hitInfo.rigidbody.AddForceAtPosition(_force, hitInfo.point, ForceMode.Impulse);
}
AudioSource.PlayClipAtPoint(soundHit, _hitInfo.point, hitSoundVolume);
bulletOrMissile.dist = _hitInfo.distance;
}
else {
bulletOrMissile.dist = 50;
}
}
}
if(Input.GetMouseButton(0)){
OnStartFire();
}
if(Input.GetMouseButtonUp(0)){
OnStopFire();
}
}
void OnStartFire() {
if (Time.timeScale == 0)
return;
firing = true;
if(muzzleFlash) muzzleFlash.active = true;
if (audio) audio.Play();
}
void OnStopFire() {
firing = false;
if(muzzleFlash) muzzleFlash.active = false;
if (audio) audio.Stop();
}
//attach this script with bullet
public class SimpleBulletOrMissile : MonoBehaviour {
public float speed = 10; public float lifeTime = 0.5f; public float dist = 100;
private float _spawnTime = 0.0f;
private Transform _tr;
// Use this for initialization
void OnEnable () {
_tr = transform;
_spawnTime = Time.time;
}
// Update is called once per frame
void Update () {
_tr.position += _tr.forward * speed * Time.deltaTime;
dist -= speed * Time.deltaTime;
if (Time.deltaTime > _spawnTime + lifeTime || dist < 0) {
// print("Destroy form bullet");
Destroy(gameObject);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
raycast spawn problem 0 Answers
FPS shooting 1 Answer
Particles are off when I shoot 1 Answer
How do i make a Railgun style effect with a raycast shot? 1 Answer