Question by
unity_8CIcfRhgN7lfcQ · Dec 26, 2020 at 02:48 PM ·
raycast
Shooting 1 raycast which hits the object 6 times
I'm working on a first person shooter and I'm using raycasts for the bullets. When I shoot one raycast it hits the object 6 times. I don't know why it's doing this. Here is the code:
using UnityEngine;
public class RaycastShooting : MonoBehaviour
{
public int damageperbullet;
public float fireringrate;
public int bulletnumber;
public float forceaplied;
public float recoil;
public float playerknockback;
public float ammoamount;
public float clipsize;
public float currentammoinclip;
public float accuracy;
public float reloadspeed;
float range = 1000f;
public Camera camera;
public GameObject player;
void FixedUpdate() {
if (Input.GetButtonDown("Fire1")) {
Shoot();
}
}
void Shoot() {
//for (int i = 0; i < bulletnumber; i++) {
RaycastHit hit;
//determines at what angle the bullet will leave the barrel
Vector3 angleofshot = new Vector3 (Random.Range(-accuracy, accuracy), Random.Range(-accuracy, accuracy), Random.Range(-accuracy, accuracy));
//pushes the object which was shot if it has a Rigidbody
if (Physics.Raycast(camera.transform.position, camera.transform.forward + angleofshot, out hit, range)) {
Debug.Log(hit.transform.name);
if (hit.transform.GetComponent<Rigidbody>() != null) {
hit.transform.GetComponent<Rigidbody>().AddForceAtPosition(camera.transform.forward * forceaplied, hit.transform.position);
}
Health objecthealth = hit.transform.GetComponent<Health>();
if (objecthealth != null) {
objecthealth.healthcounter(damageperbullet);
}
}
//adds knockback to the player
player.GetComponent<Rigidbody>().AddForce(-camera.transform.forward * playerknockback);
}
}
I am new to unity so sorry if this is a feature that I don't know about.
Comment
Best Answer
Answer by Owen-Reynolds · Dec 26, 2020 at 05:07 PM
It's probably due to calling GetButtonDown during FixedUpdate instead of Update. The raycast hits once each time, but you shoot 6 times in a row from 1 press. See the docs at https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html for an explanation. This is a common problem.