- Home /
Random Gun Jam with Array
I'm making a revolutionary war project, and the muskets back then jammed. So I can get the gun to jam with this bit of code:
if(bulletShotCount == 30 || spitfireShotCount == 7){
canShoot = false;
}
bulletShotCount
is a variable that increases by one every single time the shot is fired. So when the shot count equals 30, the gun "jams", and the player can no longer shoot. But I want it to jam randomly, as if to say, it can jam at 10, or at 7, or at 1, or at 2. So what I though I would do is make to variables:
var bulletGunJam = int[];
var spitfireGunJam = int[];
So I figured that if I made those two variables arrays, that it would choose one of the values in the array, and pick one randomly each time. It obviously didn't do that. Here's the code I used:
if(bulletShotCount == bulletGunJam || spitfireShotCount == spitfireGunJam){
canShoot = false;
}
Is there another way to make it jam randomly?
Yeah, what @timsk said- why make it complicated? Also, the way you are doing it here, you will only jam at certain times. Are you sure that's really what you want? Using @timsk's method, you could also add something in which increases the chance of the gun jam$$anonymous$$g every time it doesn't, and then reset it when it jams.
The way I would implement that method above, btw, wouldn't be by picking a number between 1 and 10. Just use a 0-1 probability (since that's how probability is calculated anyway) and compare it with Random.value.
Well, i changed my comment to an answer and added an example. Would be interested to see how you would have done it syclamoth.
Answer by timsk · Oct 19, 2011 at 09:32 AM
why not just, everytime you take a shot, pick a number between 1 and 10. if the number is higher than 5 jam the gun, if not, allow the gun to fire.
example:
var shotJamChance : int;
function JamCheck()
{
shotJamChance = Random.range(1,10)
if(shotJamChance >=5)
{
Shoot();
}
else
{
JamGun();
}
}
This would give you a 50% chance to jam, so just weight it whichever way you want, for more randomness, increase the number (so 1-50 would be more random than 1-10)
Well, my way is basically the exact same, only with numbers between 0 and 1, ins$$anonymous$$d of 1 and 10.
It works, but the only problem is, in the inspector, the shotJamChance integer changes several times a second. I only want it to change every time the player shoots. How should I do that?
Sounds like your running JamCheck() inside Update(). You need to do something like this:
function ShootGun()
{
//gun shoot code here
JamCheck()
}
Then run ShootGun() inside On$$anonymous$$ouseDown(1) or something similar. This way, you only check for a jam when the player shoots.
Your answer
Follow this Question
Related Questions
Shoot only once when clicked 1 Answer
Best way to play reload animations for a gun?? 1 Answer
How to Clone Array1 into Array2 in Unity? Using JavaScript. 0 Answers
Bullets will not fire forwards 1 Answer
arraylist stroing/passing values? 0 Answers