4
votes

I've run into an issue where the SpriteBatch doesn't draw with modified Alpha of specified "Trail". What I'm trying to do is a "fade effect" where the alpha of "Item" decreases so that it gets more transparent until it eventually gets destroyed. However it doesn't change the alpha on it? The alpha does decrease but the alpha value of the color doesn't get modified, it stays the same color and then dissapears

Here's what happens: http://dl.dropbox.com/u/14970061/Untitled.jpg

And this is what I'm trying to do http://dl.dropbox.com/u/14970061/Untitled2.jpg

Here's a cutout of the related code I'm using at the moment.

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
for (int i = 0; i < Trails.Count; i++)
{
    Trail Item = Trails[i];
    if (Item.alpha < 1)
    {
        Trails.RemoveAt(i);
        i--;
        continue;
    }

    Item.alpha -= 255 * (float)gameTime.ElapsedGameTime.TotalSeconds;
    Color color = new Color(255, 0, 0, Item.alpha);
    spriteBatch.Draw(simpleBullet, Item.position, color);
}
spriteBatch.End();
4

4 Answers

1
votes

Make sure that your call to spriteBatch.Begin() includes the necessary parameters:

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
1
votes

Don't use NonPremultiplied if you don't have to! Leave it as AlphaBlend. Read up on Premultiplied Alpha and how it was added in XNA 4.0.

The correct solution to your problem is to use the multiply operator on your colour:

Color color = Color.Red * Item.alpha/255f;

Or use the equivalent Lerp function to interpolate it to transparency:

Color color = Color.Lerp(Color.Red, Color.Transparent, Item.alpha/255f);

(Also, if you did change your blend state to non-premultiplied, to be correct you'd have to change your content import to not premultiply your textures, and ensure your content has blendable data around its transparent edges.)

0
votes

Alpha range is between 1 (fully opaque) and 0 (fully transparent), also its a float I believe. So you are going out of bounds of its range.

edit: try decreasing it by 0.1 and if its less or equal to zero, delete it

0
votes

Turns out it did work, I just used the wrong BlendState, I switched to BlendState.NonPremultiplied and now it works.