Game Development Community

dev|Pro Game Development Curriculum

TGB.fadeToAlpha

by Kevin James · 06/25/2010 (6:18 am) · 1 comments

I wanted a specific alien type to fade in and out in my game Fangorodrim. I found this topic in the forums:
www.torquepowered.com/community/forums/viewthread/50880

That gives us a fade out, but not fade in. Here is how I modified the code to do both:
function Alien::fadeToAlpha(%this, %fadeOutDelay, %fadeOutTime, %alphaTarget, %increments, %callback)
{
    %this.setBlendAlpha(%this.stealth);

    %startAlpha = %this.getBlendAlpha();
    if(%startAlpha == %alphaTarget)
    {
        %this.visible=!%this.stealth;
        return;
    }

    %minIncrements = 1;
    %maxIncrements = 100;
    %defaultIncrements = 10;
    if(%increments $= "" || %increments < %minIncrements || %increments > %maxIncrements)
    {
        %increments = %defaultIncrements;
    }

    %timeIncrement = %fadeOutTime / %increments;

    %alphaDelta = %alphaTarget - %startAlpha;
    %alphaIncrement = %alphaDelta / %increments;
    if (!%this.stealth) %alphaIncrement = %alphaIncrement / 100;
   
    if (isEventPending(%this.fadeID)) cancel (%this.fadeID);  
    %this.fadeID = %this.schedule(%fadeOutDelay, "fadingAlpha", %timeIncrement, %alphaIncrement, %alphaTarget);
}

function Alien::fadingAlpha(%this, %timeIncrement, %alphaIncrement, %alphaTarget, %callback)
{
    %currentAlpha = %this.getBlendAlpha();
    %newAlpha = %currentAlpha + %alphaIncrement;
    %this.setBlendAlpha(%newAlpha);

    if (%this.stealth) %fading = (%newAlpha > %alphaTarget);
    else %fading = (%newAlpha < %alphaTarget);
    
    if(%fading)
    {
        if (isEventPending(%this.fadeID)) cancel (%this.fadeID);  
        %this.fadeID = %this.schedule(%timeIncrement, "fadingAlpha", %timeIncrement, %alphaIncrement, %alphaTarget);
    }
    else
    {
        eval(%callback);
    }
}

Here is how the functions are called:
function Alien::goStealth(%this)
{
  %this.stealth = !%this.stealth;
  if (%this.stealth) {
     %this.fadeToAlpha(0,500,0,10);//fade out
  }
  else {
     %this.fadeToAlpha(0,500,100,20);//fade in
  }
  if (isEventPending(%this.stealthID)) cancel(%this.stealthID);
  %this.stealthID = %this.schedule(2000,"goStealth");
}

The direction of the fade is based on the "stealth" boolean property of the alien. It would be simple to convert this code to have a passed in boolean determine the fade direction. If anyone wants to see that, let me know.

About the author

Computer security, digital forensics, and platform jumper enthusiast. shells.myw3b.net/~syreal/