Raycast Shooting [Need help]
Hello! I am new to unity and C# i am trying to make my gun shoot with recoil. I think i got it to work. But some times when i shoot in the wall i don't get a bullet hole. Same with the ground.
Heres my code:
using UnityEngine;
using System.Collections;
public class PM_40 : MonoBehaviour {
public GameObject texture;
GameObject Gun;
GameObject Receiver;
float rateFire = 0.4f;
float countDown;
float speed = 10;
bool canShot = true;
bool gunCocking = false;
public AudioClip pistolSound;
public AudioClip pistolReloadSound;
public AudioClip pistolCokingSound;
float ammo = 12;
float recoil = 0.1f;
Vector3 randomHit;
// Use this for initialization
void Start () {
Gun = GameObject.Find("PM_40");
Receiver = GameObject.Find("PM-40_Top");
}
// Update is called once per frame
void Update () {
if (ammo == 0)
{
gunCocking = true;
if (Input.GetKeyDown("r"))
{
Camera.main.GetComponent<AudioSource>().clip = pistolReloadSound;
Camera.main.GetComponent<AudioSource>().Play();
gunCocking = false;
ammo = 12;
}
if (Input.GetMouseButtonDown(0) && gunCocking == true)
{
Camera.main.GetComponent<AudioSource>().clip = pistolCokingSound;
Camera.main.GetComponent<AudioSource>().Play();
}
} else
{
gunCocking = false;
}
if (canShot == false)
{
if (countDown > 0)
{
countDown -= Time.deltaTime;
}
if(countDown < 0)
{
countDown = 0;
canShot = true;
}
}
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
Debug.DrawRay(ray.origin, ray.direction * 10000, Color.yellow);
RaycastHit hit;
if(Input.GetMouseButtonDown(0) && canShot == true && ammo > 0){
transform.Rotate(0, recoil * Time.deltaTime, 0);
Camera.main.GetComponent<AudioSource>().clip = pistolSound;
Camera.main.GetComponent<AudioSource>().Play();
Gun.transform.position = new Vector3(Gun.transform.position.x, Gun.transform.position.y, Gun.transform.position.z - recoil);
if (Physics.Raycast(ray, out hit))
{
if (Input.GetMouseButton(1))
{
randomHit = new Vector3(hit.point.x + Random.Range(-0.01f, 0.01f), hit.point.y + Random.Range(-0.01f, 0.01f), hit.point.z);
}
else
{
randomHit = new Vector3(hit.point.x + Random.Range(-0.4f, 0.4f), hit.point.y + Random.Range(-0.4f, 0.4f), hit.point.z);
}
Instantiate(texture, randomHit, Quaternion.LookRotation(Vector3.up, hit.normal));
}
ammo--;
countDown = rateFire;
canShot = false;
}
}
void OnGUI()
{
GUI.Box(new Rect(Screen.width - 100, Screen.height - 30, 100, 25), "Ammo: " + ammo);
}
}
Comment
Your answer
Follow this Question
Related Questions
Range not working c# - shooting script using raycast 0 Answers
Doom/Wolfenstein 3D-style targeting system. Detect enemies in camera view? 0 Answers
Test if a bullet will hit before shooting it? 2 Answers
Any way to increase raycast range? 0 Answers
How can I make my Raycast ignore my player, but have other player's Raycasts be able to hit it? 1 Answer