Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: horusr on Tue 18/07/2017 09:34:02

Title: Timer Bar
Post by: horusr on Tue 18/07/2017 09:34:02
Hi there,

I want to add a timer bar in my game that shows how many time player has left. But I don't want it to show time in strings. I want it to be something like this(bottom right side of it):

(http://i.imgur.com/5ZylUV4.png)

And I created a button and draw rectangle on it with this code:

Code (ags) Select
int timerstime = 0;
function battle_timer()
{
  DynamicSprite* sprite = DynamicSprite.Create(60, 10);
  DrawingSurface* surface = sprite.GetDrawingSurface();
  surface.DrawingColor = 1;
  surface.DrawRectangle(timerstime/10, 0, 60, 10);
  surface.DrawingColor = 2;
  surface.DrawRectangle(0, 0, timerstime/10, 10);
  Timer.NormalGraphic = sprite.Graphic;
  surface.Release();
  Wait(1);
}


function repeatedly_execute()
{
  if (timerstime > 0)
  {
    battle_timer();
    timerstime--;
  }
  else
  {
    gBattle.Visible = false;
  }
}


And it kinda works. The problem is if I don't add Wait() command it does not show bar at all.
Title: Re: Timer Bar
Post by: Khris on Tue 18/07/2017 09:43:02
That's because, as is explained in the dozens of existing threads about this exact same problem (although they are admittedly hard to find), you're creating the DynamicSprite inside the function, which means the sprite doesn't survive the function ending.

DynamicSprite* sprite;

function battle_timer()
{
  if (sprite == null) sprite = DynamicSprite.Create(60, 10);
  DrawingSurface* surface = sprite.GetDrawingSurface();
  ...
Title: Re: Timer Bar
Post by: horusr on Tue 18/07/2017 09:53:17
Oh, I am really sorry for asking then. I searched forum for timers but now I see it is not about timers at all.
I tried to move "DynamicSprite* sprite = DynamicSprite.Create(60, 10);" to top of the script once but that gave me error.
So we should use ".Create" comman in function but not dynamic sprite itself? Code now works btw.
Title: Re: Timer Bar
Post by: Khris on Tue 18/07/2017 13:41:01
The error tells you why simply moving the line doesn't work: you cannot assign inital values to global pointers. int myVar = 5; works outside of functions, but DynamicSprites are script objects, not primitive types.