- Home /
shooting problem with raycasting
hello can someone tell me why the reload isnot working and how can i do if the player hold the mouse it should shoot and if he just clicked just shoot ones here is the script. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class shootak47 : MonoBehaviour
{
public Transform wheretoshoot;
float range = 100f;
bool ishooting = false;
bool isreloading = false;
int bullet = 100;
int currentbullet;
void Start()
{
currentbullet = bullet;
}
// Update is called once per frame
void Update()
{
if(currentbullet > 0 )
{
StartCoroutine(delaybetweenshots());
}
if(Input.GetButton("Fire1"))
{
if (!ishooting)
{
shooting();
currentbullet--;
}
}
}
public void shooting ()
{
if (!isreloading)
return;
if(!ishooting)
{
RaycastHit Hit;
if (Physics.Raycast(wheretoshoot.position, transform.forward, out Hit, range))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
}
}
}
IEnumerator delaybetweenshots()
{
isreloading= false;
yield return new WaitForSeconds(2f);
currentbullet = bullet;
isreloading = true;
}
}
Answer by KoenigX3 · May 29, 2020 at 07:22 PM
const float fireDelay = 0.25f;
float delayTimer = 0;
void Start()
{
currentbullet = bullet;
}
void Update()
{
if(delayTimer > 0)
{
delayTimer -= Time.deltaTime;
if(delayTimer < 0) delayTimer = 0;
}
if(Input.GetButton("Fire1"))
{
if(delayTimer == 0)
{
Shoot();
delayTimer = fireDelay;
}
}
}
void Shoot()
{
if(currentbullet == 0) return;
// Your shooting code with the raycast goes here
currentbullet--;
if(currentbullet == 0) StartCoroutine(Reload());
}
IEnumerator Reload()
{
yield return new WaitForSeconds(2f);
currentbullet = bullet;
}
thank you it worked but when it the currentbullet is 0 it donot reload
I've just tested it, it works for me. What did you put in the Shoot() method? You only need this part:
RaycastHit Hit;
if (Physics.Raycast(wheretoshoot.position, transform.forward, out Hit, range))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
}
Also check if you have put return in this method. You need to make sure that it runs those 2 lines in the end, so do not use any return aside from the one i've put there.
Your answer
Follow this Question
Related Questions
Random Raycast inside crosshairs 1 Answer
Ray curve for bullet gravity effect, or any way to make it 1 Answer
Problem in Shooting Accuracy 0 Answers
How to stop enemies from shooting each other 1 Answer
Shoot with ray cast angle 1 Answer