- Home /
Make a value PingPong between 0-100, and reset to 0 after.
Hey,
I'm trying to make a 'power' bar that while holding down the mouse button, 'pingpongs' between 0 and 100
void Update()
{
if (Input.GetMouseButton(0))
{
weakPower = Mathf.PingPong(Time.time * 1, 100);
Debug.Log("Current Power: " + weakPower);
}
else if (Input.GetMouseButtonUp(0))
{
Power = weakPower;
Fire(Power);
weakPower = 0;
Power = 0;
}
}
However, when I release, it's supposed to grab that value, 'fire' and then when I hold it down again, it needs to start from 0 again and do the same thing.
What actually happens is that it keeps PingPong-ing between 0,100 resulting in the fact that quickly clicking should output a low value everytime, but it doesn't.
Long story short, I need a value that goes up & down between 0 and a 100 whilst I'm holding the mouse button, after release, sets back down to 0, and when being pressed again, does the same thing.
Answer by Bunny83 · Nov 25, 2017 at 05:56 PM
First of all what's the point of the Power variable?
This code:
Power = weakPower;
Fire(Power);
weakPower = 0;
Power = 0;
Can be simplified to
Fire(weakPower);
weakPower = 0;
Your next problem is your pingpong doesn't "start" and any particular level. It always starts at the current time value which can be anything depending on when the user starts pressing down the button. You probably don't want to use Time.time here but your own variable which you increase manually
float time = 0f;
void Update()
{
if (Input.GetMouseButton(0))
{
time += Time.deltaTime;
weakPower = Mathf.PingPong(time, 100f);
Debug.Log("Current Power: " + weakPower);
}
else if (Input.GetMouseButtonUp(0))
{
time = 0f;
Fire(weakPower);
weakPower = 0f;
}
}
Thanks dude, this worked,
I had the "Power" variable created cus I was messing around with stuff and haven't cleaned up my code yet, it wasn't doing any harm yet, so I just let it stick around for a bit :p Thanks for helping me remember though!