- Home /
How to Implement First Shot Accuracy?
I am making a fps in unity and i have implemented weapon accuracy by adding random number with the range of my "bulletSpread" to the camera.transform.forward. It works perfectly however I want the first shot from a weapon to be 100% accurate (or close to it). Here is the code for my raycast.
Also for some reason the debug.drawray is not working
rayDirection = fpsCam.transform.forward;
rayDirection.x += Random.Range(-bulletSpread, bulletSpread);
rayDirection.y += Random.Range(-bulletSpread, bulletSpread);
rayDirection.z += Random.Range(-bulletSpread, bulletSpread);
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, rayDirection, out hit, range))
{
Debug.Log(hit.transform.name);
Debug.DrawRay(fpsCam.transform.position, rayDirection);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
GameObject impactGo = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGo, .1f);
}
Answer by Horschty · Jun 05, 2018 at 07:57 AM
private void Shoot(bool useSpread) {
// ...
if(useSpread) {
rayDirection.x += Random.Range(-bulletSpread, bulletSpread);
rayDirection.y += Random.Range(-bulletSpread, bulletSpread);
rayDirection.z += Random.Range(-bulletSpread, bulletSpread);
}
// ...
}
void Update() {
// GetMouseButtonDown will only fire on the first frame the mouse is pressed,
// this would be our first shot
if(Input.GetMouseButtonDown(0)) {
// First frame mouse is down, don't use spread.
Shoot(false);
} else if(Input.GetMouseButton(0)) {
// Mouse is held down, use spread.
Shoot(true);
}
}
Answer by WireShark77 · Jun 05, 2018 at 11:39 AM
Thank you for the reply I will try this when I get home my only question is that since not all of my weapons are automatic, won’t those have 100% accuracy on all of their shots?
Yes I assumed an automatic weapon that fires as long as the mouse button is held down. For other weapons you would have to define what being the first shot means. The first shot per game? The first shot since the start of the gameObjects life i.e. the first time the Shoot() method gets called? For that you could have a private bool isFirstShot, initialize that to true, at the end of the Shoot() method or after calling it set it to false. Then just set it to true again whenever you want the next shot to count as the first shot again. Something like:
// Same code as above plus
private bool isFirstShot = true;
// ...
bool useSpread = true;
if(isFirstShot) {
useSpread = false;
}
Shoot(useSpread);
isFirstShot = false;
Thank you for your quick response, and I think this will work
Your answer
Follow this Question
Related Questions
How can i make a raycast in my fps game? 1 Answer
Weapon random movement 0 Answers
Fps Ammo pickup problem(programming noob) 1 Answer
How to give your enemy gun inaccuracy 1 Answer
Aiming down sights 4 Answers