- Home /
Using modulus when score climbs in odd integers.
I enable a powerup every 50 points. I would use this in previous builds:
if (score %50==0 && score !=0)
powerUp = true;
Now I've added score multipliers so "score" no longer increases in increments of 1. It'll climb at 2x, 3x, 4x, etc. Often the score will pass right by 50, 100, 150, 200 without the player ever receiving the power-up.. since "score" isn't ever an exact multiple of 50.
If I use some sort of greater-than check, the powerup is ALWAYS true, rather than just being activated once as a reward.
How do I active the power up ONCE every 50 points?
Answer by DennisDuty · Jul 07, 2015 at 04:35 AM
After a few hours the answer I ultimately arrived to was very simplistic.
private int nextPowerUp = 50;
void powerUpConditions(){
if (score >= nextPowerUp && powerUp==false)
{
powerUp=true;
nextPowerUp +=50;
}
}
The powerUp being a bool ensures only 1 powerup accrues at a time... you either have one or you don't. The # is easy to swap out with a variable if I want the increments to change over time.
Answer by AlwaysSunny · Jul 07, 2015 at 04:13 AM
Bit longer than necessary, but it's readable. This will only trigger one event per score change. In other words, if your score was 0 and just became 500, the event will only be triggered once and not 10 times. To trigger the event retroactively like that, consider logic which records the difference between the new and old scores, uses a loop to subtract the factor (50) from that difference and triggers the event each iteration, then stops when the remainder is less than the factor.
private float factor = 50f;
private float nextScoreLevel = 50f;
private float score;
public float Score {
get { return score; }
set {
if (value >= nextScoreLevel) {
float rounded = Mathf.Round( value / factor ) * factor;
nextScoreLevel = ( value < rounded ) ? rounded : rounded + factor;
// fire your event here, we just hit the next multiple of 50
}
score = value;
}
}
Your answer
Follow this Question
Related Questions
Score not adding? 3 Answers
multiplayer score profile 1 Answer
Collecting and add points 1 Answer
How to connect a database 1 Answer
Score going up like crazy 1 Answer