- Home /
Rate of fire c# with joystick.
Im trying to use the right joystick in my android game to fire plasma bolts automatically.
My question is why this block of code works: if (Input.GetKey(KeyCode.Space) && Time.time >= nextFire) { nextFire = Time.time + fireRate; FireBullet(); }
When this doesnt:
if (RightJoyStick.position.x != 0 || RightJoyStick.position.y != 0 && Time.time >= nextFire)
{
nextFire = Time.time + fireRate;
FireBullet();
}
Answer by rutter · Nov 06, 2013 at 01:27 AM
Because &&
has a higher precedence than ||
in .NET
Given some booleans a
, b
and c
, this expression:
if (a || b && c)
Is actually closer to this:
if (a || (b && c))
When you seem to mean this:
if ((a || b) && c)
Whenever you rely on a particular grouping of logical operators, it's usually a good idea to specify that yourself.
You could provide parens:
if ((RightJoyStick.position.x != 0 || RightJoyStick.position.y != 0) && Time.time >= nextFire) {
...
}
Or use temporary variables:
bool joystickMoved = RightJoyStick.position.x != 0 || RightJoyStick.position.y != 0;
bool canFire = Time.time >= nextFireTime;
if (joystickMoved && canFire) {
...
}
Thanks. I though I had tried that before but when I did it this time it worked.
$$anonymous$$ind of feel dumb, lol. This is coding 101
Every language does it juuuust a bit differently. Habits that worked in one environment might not work in another. Coding is harsh!
Your answer
![](https://koobas.hobune.stream/wayback/20220613121321im_/https://answers.unity.com/themes/thub/images/avi.jpg)