- Home /
Incrementing a value repeatedly
Hey guys,
I thought I'd start a new thread as the old issue I was having is solved. New issue, new thread. I'm not quite sure how to word it clearly so I'll give it my best try lol.
I'm basically incrementing a value as the player races around the track. This value represents their progress across the track.
I have a series of checkpoints that the racer races through. Each time the player goes through a checkpoint it increments the progress tracker by 100. I wanted to make the progression integer more accurate so I could work out racer positions. So I started tracking the distance between points. Using the distance between points I was able to work out how far away from the previous point a racer was and how close he was to the next one. I turned this value into a percentage to make it easier to handle.
So instead of incrementing the progress value at each checkpoint I've moved this code to the update so it can constantly track the player's progress.
Obviously my issue is now with my code in the update. It simply keeps adding on the percentage to the progress int. So for example say the racer is at check point 4, the progress int should be 400, right? If I'm 25% along the way to checkpoint 5 It should be 425, but because of the nature of update it adds the percentage on every frame and things get crazy.
To summarise what I'm asking is if it's possible to increment a number on the update function but to only add the difference. So for example my progress is at 400, but I add 20 to it. It should become 420, but when adding 21 to it should only become 421.
Everything I think of just seems unusually elaborate and I keep thinking there must be a simpler solution.
Sorry if my question isn't too clear I wasn't too sure how to word it.
Thanks in advance.
PS I'm working in C#
Answer by aldonaletto · Mar 30, 2013 at 02:44 AM
I would keep the two things in different variables: a baseProgress variable set by each checkpoint, and a relativeProgress variable that shows the percentage: calculate relativeProgress in Update and display the sum of both - something like this:
int baseProgress = 0;
int relativeProgress = 0;
float segmentSize;
void OnTriggerEnter(Collider other){
if (other.tag == "Checkpoint"){
baseProgress += 100;
}
}
void Update(){
relativeProgress = Mathf.RoundToInt(100 * curDistance / segmentSize);
int curProgress = baseProgress + relativeProgress;
...
}
Way too many late nights I think! It just didn't cross my $$anonymous$$d to have it set up like that. Thanks for co$$anonymous$$g to my rescue. Really appreciate it.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Incrementing an variable till it reaches a certain amount? 1 Answer
Incrementing a string array (c#) 2 Answers
Strange error with increment-decrement between scripts 1 Answer