Can anybody see what's wrong with my math here?

Started by
1 comment, last by Utwo 21 years ago
I'm blitting a bitmap with an alpha value. The alpha value for this bitmap is not per-pixel, and it changes over time as follows: * Between 0 and 2500 milliseconds, the alpha value gradually rises from 100 to 200. * Between 2501 and 3000 milliseconds, the alpha value decreases gradually from 200 to 0. So basically, it's an animation from semitransparent, to almost opaque, to completely transparent. To accomplish this, each frame I come up with a new alpha value using the following function:
    
int GetAlpha()
{

 int lapsed = GetTickCount() - anim_start;
 int result;

 if(lapsed <= 2500)
 {

  int x = (lapsed / 2500) * 100;
  result = x + 100;

 }
 else
 {

  lapsed -= 2500;
  int x = (lapsed / 500) * 200;
  result = 200 - x;

 } 
 
 return result;

}
    
But what ends up happening when I run this program is it appears as though the alpha value remains at 100 (or some similar number) for 2.5 seconds, and for the last .5 seconds it's at 200 or so. There's no gradual change at all. Looking at my function, is there something wrong with my math that's causing this to happen? [edited by - utwo on March 22, 2003 10:18:20 PM]
---signature---" Actually, at the time, I didn't give a damn about the FoxNews issue... just that you would come swooping in with your Super Mith cape flapping behind you and debunk it just because it didn't happen in your living room." - InnocuousFox
Advertisement
The problem is in these two lines:

int x = (lapsed / 2500) * 100;int x = (lapsed / 500) * 200; 


They should be:

int x = (int) (lapsed / 2500.0 * 100.0);int x = (int) (lapsed / 500.0 * 200.0); 



The problem is dividing an integer by an integer in C++ gives you an integer, not a floating point value. So for the first 2499 milliseconds, lapsed / 2500 is 0. Then it jumps to 1 for the last millisecond. Similarly for the first 499 milliseconds of the second part of the animation lapsed / 500 is returning 0, then it jumps to 1 for the last millisecond. So instead of a gradual transition you get constant values with some brief spikes.
When you do :

int x = (lapsed / 2500) * 100;  


The compiler first evaluate (lapsed / 2500), which is always 0 when lapsed is less than 2500. You should multiply first.

int x = (lapsed * 100) / 2500;  

This topic is closed to new replies.

Advertisement