- Home /
when float is less then zero, do action once
I'm making a game where time slows down when you aim. There's a timer so that you can't aim forever. When the timer goes off, I want the gun to move to the right once, but I can't seem to figure it out.
I'm fairly new to Unity, so any help would be appreciated.
Here's the code:
public float currentAim;
public float aimWait;
public bool gunAiming;
public bool gunTimeout;
public bool gunMoved;
public bool gunMovedTrue;
void Start()
{
currentAim = maxAim;
gunAiming = false;
aimWait = 1f;
gunMoved = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
if(currentAim <= 0 && gunMovedTrue)
{
gunMoved = true;
gunMovedTrue = false;
}
else
{
gunMoved = false;
}
if(currentAim <= 0)
{
//make guntimeout always true
gunTimeout = true;
//make gunmoved true once and then false
// gunMoved = true;
}
else
{
gunTimeout = false;
gunMoved = false;
}
if(gunTimeout)
{
gunMovedTrue = true;
}
if(Input.GetKeyDown(KeyCode.Mouse1))
{
gun.transform.Translate(Vector3.right);
gunAiming = true;
}
if (Input.GetKeyUp(KeyCode.Mouse1))
{
gun.transform.Translate(Vector3.left);
gunAiming = false;
}
Aim();
if (Input.GetKey(KeyCode.Mouse1))
{
gunAiming = true;
}
else
{
gunAiming = false;
}
}
void Aim()
{
if (gunAiming)
{
if (gunTimeout)
{
if (gunMoved)
{
gun.transform.Translate(Vector3.left);
gunMoved = false;
}
else
{
Time.timeScale = 1f;
camera.fieldOfView = 60;
}
}
else
{
Time.timeScale = 0.1f;
camera.fieldOfView = 45;
currentAim -= Time.deltaTime * 10;
}
}
Answer by sacredgeometry · Dec 28, 2020 at 06:57 PM
You could do it a few ways. I would use c#s events/ delegates personally but the easiest way I can think of is just to add it to the property setter.
i.e.
public bool GunTimeout;
private float _currentAim = MaxAim;
public float CurrentAim
{
get
{
return currentAim;
}
set
{
GunTimeout = value <= 0.0f;
_currentAim = value;
}
}
This way every time you set the CurrentAim to another value it updates the GunTimout bool with the correct value.
I am not sure what you mean. I haven't written a function. I have just written a field and a field backed property.
Your answer
![](https://koobas.hobune.stream/wayback/20220613022309im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to move gun from middle of screen to right of screen? 1 Answer
WaitForSecond Corountine Sleep Time Varies 2 Answers
Weapon random movement 0 Answers
FPS - Attach a gun to hands and move arms when aiming up and down 1 Answer
Gun Rotation Sway 0 Answers