褪色算法不起作用?

时间:2017-03-18 18:21:10

标签: java multithreading algorithm colors fade

我正在尝试在两种颜色和一个计时器之间创建一个渐变/过渡颜色算法;计时器将确定颜色在彼此之间交换的速度。唯一的问题是:我添加的渐变过渡对象越多,它们就越快。例如:如果我添加一个StandardFade(类)对象,它将在我给它的计时器(alpha,代码中)运行。但是,如果屏幕上出现更多“淡入淡出”的对象,则计时器不再相关,并且它们都以相同的速率运行,每个对象的速度越来越快。任何人都可以解释原因吗?

import java.awt.Color;
import java.awt.Graphics2D;

public class StandardFade {

private static float time = 0;
private static boolean firstColor = true;

private Color color1;
private Color color2;
private double alpha;

private Color fadeColor;

/**
 * Lines that implement the 
 * r,g and b values come from Princeton University; I will author
 * them in at the bottom.
 * 
 * Method takes two parameters and fades them into one another according to a 
 * timer/clock value: alpha.
 * @param c1 First color to be used. 
 * @param c2 Second color to be used. 
 * @param alpha How fast colors should shift. 0 <= n <= 1. 
 * Closer value is to zero, the longer it will take to shift.
 * ***Important note about alpha: for non-seizure inducing colors, alpha <= .0005***
 * 
 * The issue that is occurring is that, no matter what I do, no matter if I make 
 * different StandardFade objects and assign them, they will always render at the 
 * same rate, and faster and faster, depending on how many objects are fading.
 *
 * @return new Color based on r, g, and b values calculated.
 * 
 * @author (Only code utilized was lines 58-60):
 * http://introcs.cs.princeton.edu/java/31datatype/Fade.java.html
 */
public StandardFade(Color c1, Color c2, double alpha){
    this.color1 = c1;
    this.color2 = c2;

    this.alpha = alpha;
}

public void tick() {

    if(time <= 1f && firstColor){
        time += alpha;
    }

    else{
        firstColor = false;
    }
    if(time >= 0f && !firstColor)
        time -= alpha;
    else{
        firstColor = true;
    }

    //System.out.println(time);

    short r = (short) (time * color2.getRed()   + (1 - time) * color1.getRed());
    short g = (short) (time * color2.getGreen() + (1 - time) * color1.getGreen());
    short b = (short) (time * color2.getBlue()  + (1 - time) * color1.getBlue());

    if(r > 255) r = 255;
    if(g > 255) g = 255;
    if(b > 255) b = 255;

    if(r < 0) r = 0;
    if(g < 0) g = 0;
    if(b < 0) b = 0;


    this.fadeColor = new Color(r, g, b);
}

public Color getColor(){
    return this.fadeColor;
}

以下是制作帧的实际类:StandardFade

{{1}}

2 个答案:

答案 0 :(得分:1)

  

唯一的问题是:我添加的渐变过渡对象越多,它们就越快

private static float time = 0;

您正在使用静态变量。此变量由ColorFade类的所有实例共享。因此每个渐变对象都会更新相同的变量。

不要使用静态变量(只需删除static关键字)。每个衰落对象都需要自己的“时间”变量。

private float time = 0;

我还质疑firstColor变量是否应该是静态的。

答案 1 :(得分:0)

这需要经过相当多的代码(尝试在将来尽可能减少你的问题),但根据你对问题的描述 - 你拥有的对象越多越快 - 我猜你的问题是这一行:

private static float time = 0;

我假设你知道在类实例之间共享静态字段。他们不会各自存储自己独立的价值。

这会导致问题,因为每次调用tick方法时,每个实例都会递增时间值。当只有一个实例时,这是可以的,但是当有更多时,这是有问题的。

只需删除static关键字即可正常运行:

private float time = 0;