Search code examples
c#game-engine2d-games

Game Object invisible for a given time


Good day everyone, currently I am developing a simple 2D game using SWINGAME. I have set a collision between 2 objects. So when they collide, I want to temporarily make one of them invisible for a certain time. I am stuck about the time component, let's say I want the object to be invisible for 3 seconds after that it will change back to the default object. Below are the two images, if the collision is true then it will display image2, or else display image1. BTW I use a different image to indicate the invisibility. Here's my code.

Player class:

 public void Draw ()
        {
            if (invisible == true) {
                if(elapsedTime <= 3.0){

                elapsedTime += elapsedTime;
                SwinGame.DrawBitmap ("image2.png", (float)X, (float)Y);

                  } 
            }else {
                elapsedTime = 0;
                SwinGame.DrawBitmap ("image1.png", (float)X, (float)Y);
            }
        }

  public bool Invisible {
        get { return invisible; }
        set { invisible = value; }
       }

Object Collision class :

{... //Some codes

    for(int i = 0; i < _obstacles.Count; i++)
    {
      if (_obstacles [i] is Invisible) {
         p.Invisible = true;
         p.Draw ();
           }
    }
//Some codes ...}

Solution

  • This should help you to calculate the time accurately by using the StopWatch class:

    //somewhere in your code
    Stopwatch sw = new Stopwatch();
                sw.Start();
    
    public void Draw ()
            {
                if (invisible == true) {
                    if(sw.ElapsedMilliseconds <= 3000){
    
                    SwinGame.DrawBitmap ("image2.png", (float)X, (float)Y);
    
                      } 
                }else {
                    sw.Restart();
                    SwinGame.DrawBitmap ("image1.png", (float)X, (float)Y);
                }
            }