Increasing score based on speed
I am having trouble increasing score based on speed of the car with a few lines of code. I know how to do it with score vs time with
yield return new WaitForSeconds(x);
, and I know how to this with 5 or 6 conditions and 20 lines of code ,but I wanted to do this with a few lines of code. It's possible ?.
What I want is:
Score + = 1 point every 1 second if car speed = 1
Score + = 1 point every 0.8 seconds if car speed = 3
Score + = 1 point every 0.6 seconds if car speed = 6
Score + = 1 point every 0.4 seconds if car speed = 9
Score + = 1 point every 0.2 seconds if car speed> 9
I m using two Coroutines, one for score and another for speed, activated on Start function:
private IEnumerator ChangeSpeed()
{
while (true){
yield return new WaitForSeconds(1);
if(speed < 2.0f || speed < 9.0f && gameStart){
speed += 3.0f;
}
if(speeding)
velocity = speed + 1f;
else
velocity = speed;
}
}
private IEnumerator ChangeScore()
{
while (true){
yield return new WaitForSeconds(1);
if(gameStart){
scoreNum += 1;
scoreText.text = scoreNum.ToString();
}
}
}
Answer by Major · Jun 10, 2017 at 07:12 PM
What if you plotted an equation that returned the time interval between each point assignment?
Your independent variable being speed (x-axis) and your dependent variable being the time interval (y-axis). If you plot the function
y = -0.1x + 1.1
you can return any time interval value you want between 1 and 9. Then you plug in this result into your WaitForSeconds to achieve the appropriate wait time. This could look something like this:
float speed = Mathf.Truncate(objSpeed); //Edit: needed so that you always test an integer
if (speed >= 1 && speed <= 9) {
waitTime = -0.1 * speed + 1.1;
} else if (speed > 9) {
waitTime = 0.2f;
} else if (speed < 1) {
waitTime = Mathf.Infinity;
}
By truncating the objSpeed and plugging in the result, you can setup these boundaries. It's also important to note that waitTime should be a global variable to ensure that it's value carries from previous frames.
I hope that this helps to answer your question. Sorry it was so long, but I wanted to try to build something from the ground up with an alternative approach. This code is untested, but I hope the theory at least comes across if nothing else. I hope this helps!
Worked very well. I only had to adjust values to achieve the desire effect.
Thanks! God bless you.