2
votes

I have problem with animate image, when transforming from transparent image to opaque image.

If I animate image from opaque image to transparent image, works fine. But, if I animate image from transparent image to opaque image, It's non-functional.(that's problem)

Sample code:

Animate from opaque to transparent: (all is OK, it's functional)

//Define variables (in construct):

float AlphaTime = 3500f; // total animate time (at milliseconds)
float AlphaTimeSubtract = 3500f; // at milliseconds
Color color = Color.White;

//Update method:

AlphaTimeSubtract -= (float)(gameTime.ElapsedGameTime.TotalMilliseconds); // abate number of elapsed time (for milliseconds) 
color *= MathHelper.Clamp(AlphaTimeSubtract / AlphaTime, 0, 1);

//Draw merhod:
spriteBatch.Draw(texture, position, color);

Animate from transparent to opaque : (that is problem, it is non-functional) !!!

Result is invisible sprite!(it's wrong)

Correct result should be: animate sprite from transparent to opaque.

//Define variables (in construct):

float AlphaTime = 3500f; // total animate time (at milliseconds)
float AlphaTimeSubtract = 3500f; // at milliseconds
Color color = Color.White;

//Update method:

AlphaTimeSubtract -= (float)(gameTime.ElapsedGameTime.TotalMilliseconds); // abate number of elapsed time (for milliseconds) 
color *= MathHelper.Clamp(Math.Abs(AlphaTimeSubtract - AlphaTime ) / AlphaTime , 0, 1);

//Draw merhod:
spriteBatch.Draw(texture, position, color);

MathHelper.Clamp()

Math.Abs(): return absolute value

What am I doing wrong?

1
colors multiplier = float number from 0 to 1. 0 = transparent , 1 = opaqueuser1675817

1 Answers

1
votes

EDIT : Sorry, I had the flash of inspiration late :)

Your code doesn't work because when the Update() method is called the first time the Alpha of your color becomes 0, because the value that Math.Abs(AlphaTimeSubtract - AlphaTime ) / AlphaTime returns is very closed to 0.0f so then for whatever number you will multiply color, it remains 0. Infact this problem didn't happen in the first case because the logic says to decrease it starting from 1.0f. So in this case you have to decrease the alpha starting everytime from 255. So this should work:

//Initialize it to 0
float AlphaTimeSubtract = 0.0f;

//Then in the update method increase it (The inverse logic you used in the opaque --> transparent effect)
AlphaTimeSubtract += (float)(gameTime.ElapsedGameTime.TotalMilliseconds);
color = Color.White * MathHelper.Clamp(AlphaTimeSubtract / AlphaTime , 0, 1);

I modified the code to make it more easier compared to the first effect (opaque -> transparent).