如何使用deltatime更改背景颜色

时间:2018-03-30 07:08:13

标签: java swing background

如何使用deltatime更改背景颜色?

具有2个随机颜色的2个元素的数组,需要根据deltatime更改颜色。

像这样:

deltatime的第一个刻度= color2 [0];

deltatime的第二个刻度= color2 [1];

第三个tick = color2 [0]

ë

C

它使用循环:

privite void fillArray() {
  for (int i = 0; i <c2.length ; i++) {
     c2[i] = new Color ((int)(Math.random() * 256f), (int) (Math.random() * 256f), (int) (Math.random() * 256f));
  }
}

void render(GameCanvas gameCanvas, Graphics g) {
  for (int i = 0; i < c2.length; i++) {
     g.setColor(c2[5]);
  }
  g.fillRect(gameCanvas.getX(), gameCanvas.getY(), gameCanvas.getWidth(), gameCanvas.getHeight());
}

但我需要使用deltatime

渲染:绘制背景

void render(GameCanvas gameCanvas, Graphics g) {
  g.fillRect(gameCanvas.getX(), gameCanvas.getY(), gameCanvas.getWidth(), gameCanvas.getHeight());
}

void update(GameCanvas gameCanvas, float deltaTime) {
    //  here is should be code to change color. plz help
}

1 个答案:

答案 0 :(得分:0)

在我的情况下看起来像这样: 但这没有deltatime。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;



public class Background extends JPanel {
   Color drawColor = Color.BLACK;
   private final int delay = 150;


   public Background() {
   //   repaint();
      ActionListener action = new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {

            Color color = new Color((int) (Math.random() * 256f), (int) (Math.random() * 256f), (int) (Math.random() * 256f));
            drawColor = color;
         }
      };

      Timer t = new Timer(delay, action);
      t.setRepeats(true);
      t.setInitialDelay(0);
      t.start();
   }

   public void render(Graphics g, GameCanvas gameCanvas){
      g.setColor(drawColor);
      g.fillRect(gameCanvas.getX(), gameCanvas.getY(), gameCanvas.getWidth(), gameCanvas.getHeight());
   }
}