Timer Bar

Started by horusr, Tue 18/07/2017 09:34:02

Previous topic - Next topic

horusr

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):



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

Code: ags
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.

Khris

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.

Code: ags
DynamicSprite* sprite;

function battle_timer()
{
  if (sprite == null) sprite = DynamicSprite.Create(60, 10);
  DrawingSurface* surface = sprite.GetDrawingSurface();
  ...

horusr

#2
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.

Khris

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.

SMF spam blocked by CleanTalk