So im trying to make a fps game but every time i click “Fire 1” it shoots a raycast and hit enemy without having my gun in position Here is my code for the gun/shooting:
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 30f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
private float nextTimeToFire = 0f;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot ()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
}
and here is my script for my weapon pickup:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponPickup : MonoBehaviour
{
public Transform equipPosition;
public float distance = 10f;
public GameObject currentWeapon;
public GameObject wp;
bool canGrab;
private void Update()
{
ChekWeapons();
if (canGrab)
{
if (Input.GetKeyDown(KeyCode.E))
{
if (currentWeapon != null)
Drop();
PickUp();
}
}
if (currentWeapon != null)
{
if (Input.GetKeyDown(KeyCode.Q))
Drop();
}
}
private void ChekWeapons()
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, distance))
{
if (hit.transform.tag == "CanGrab")
{
Debug.Log("I can grab it!");
canGrab = true;
wp = hit.transform.gameObject;
}
}
else
canGrab = false;
}
private void PickUp()
{
currentWeapon = wp;
currentWeapon.transform.position = equipPosition.position;
currentWeapon.transform.parent = equipPosition;
currentWeapon.transform.localEulerAngles = new Vector3(0f, 180, 0f);
currentWeapon.GetComponent<Rigidbody>().isKinematic = true;
}
private void Drop()
{
currentWeapon.transform.parent = null;
currentWeapon.GetComponent<Rigidbody>().isKinematic = false;
currentWeapon = null;
}
}
For some reason i can shoot without the gun Pls help me im new to making games