如何逐渐改变Monogame中的背景颜色

时间:2017-03-14 01:32:14

标签: c# monogame

我是编程的新手,也是c#的新手,但我正在尝试制作2D游戏。我创建了一个Background类和一个Close类,Close类用于我想要实现的退出按钮。我想要实现的是当我释放关闭按钮时,背景将逐渐降低,从白色到深白色。问题是我不知道如何真正编写代码。这是我的代码的视图。

关闭班级

private Texture2D texture;
private Vector2 position;
private Rectangle bounds;
private Color color;
MouseState oldstate;

public Close(Texture2D texture, Vector2 position){
  this.texture = texture;
  this.position = position;
  bounds = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
  color = new Color(40, 40, 40);
}

public void Update(GameTime gameTime){
  MouseState state = Mouse.GetState();
  Point point = new Point(state.X, state.Y);
  if(bounds.Contains(point) && !(state.LeftButton == ButtonState.Pressed)){
    color = new Color(235, 50, 50);
  } else if((!(bounds.Contains(point)) && (state.LeftButton == ButtonState.Pressed)) || (!(bounds.Contains(point)) && (state.LeftButton == ButtonState.Released))){
    color = new Color(40, 40, 40);
  }
  if((state.LeftButton == ButtonState.Pressed) && (oldstate.LeftButton == ButtonState.Released) && (bounds.Contains(point))){
    color = new Color(172, 50, 50);
  }
  if((state.LeftButton == ButtonState.Released) && (oldstate.LeftButton == ButtonState.Pressed) && (bounds.Contains(point))){

  }
  oldstate = state;
}

public void Draw(SpriteBatch spriteBatch){
  spriteBatch.Draw(texture, position, color);
}

背景课

public Color color;

public Background(Color color){
  this.color = color;

}

public void Update(GameTime gameTime){

}

为了更具体一点,我希望在Background类中更改颜色,并且能够通过Close类调用它。另外,请记住,在Game1类中指定了背景颜色,并且也从它调用了Update方法。

无论如何,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我会做的是这样的事情,虽然我对表格没有很多经验,所以它可能会或可能不会按预期工作。

您可以根据需要通过SyncFadeOut()/AsycFadeOut()课程致电Close

同步(阻止)版本:

public void SyncFadeOut()
{
     // define how many fade-steps you want
     for (int i = 0; i < 1000; i ++)
     {
         System.Threading.Thread.Sleep(10); // pause thread for 10 ms

         // ----
         // do the incremental fade step here
         // ----
     }
}

异步(非阻塞)版本:

System.Timers.Timer timer = null;

public void FadeOut(object sender, EventArgs e)
{
    // ----
    // do the incremental fade step here
    // ----

    // end conditions
    if ([current_color] <= [end_color])
    {
        timer.Stop();
        // trigger any additional things you want, like close window
    }
}

public void AsyncFadeOut()
{
    System.Timers.Timer timer = new System.Timers.Timer(10); // triggers every 10ms, change this if you want a faster/slower fade
    timer.Elapsed += new System.Timers.ElapsedEventHandler(FadeOut);
    timer.AutoReset = true;
    timer.Start();
}