How would I fade a color between minimum and maximum values in Java?

时间:2016-04-04 20:57:55

标签: java colors

Sorry if it's not clear from the title. I don't quite know how to explain, but the code that I tried is this:

package bouncingSquares;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;

public class Particle extends GameObject{

private Handler handler;

Random r = new Random();

private int redVel = 1;
private int greenVel = 1;
private int blueVel = 1;

private int red = (int)(Math.random() * 256);
private int green = (int)(Math.random() * 256);
private int blue = (int)(Math.random() * 256);

private Color color = new Color(red, green, blue);


public Particle(int x, int y, ID id, Handler handler) {
    super(x, y, id);
    this.handler = handler;

    velX = (float) (Math.random() * 11) - 5;
    while(velX == 0){
        velX = (float) (Math.random() * 11) - 5;
    }

    velY = (float) (Math.random() * 11) - 5;
    while(velY == 0){
        velY = (float) (Math.random() * 11) - 5;
    }


}

public Rectangle getBounds(){
    return new Rectangle((int)(x), (int)(y), 16, 16);
}

public void tick() {
    //red += redVel;
    //green+= greenVel;
    //blue += blueVel;

    if(red <= 0 || red >= 255) redVel *= -1;
    if(green <= 0 || green >= 255) greenVel *= -1;
    if(blue <= 0 || blue >= 255) blueVel *= -1;

    BouncingSquares.clamp(red, 0, 255);
    BouncingSquares.clamp(green, 0, 255);
    BouncingSquares.clamp(blue, 0, 255);

    color = new Color(red, green, blue);

    x += velX;
    y += velY;

    if(x <= 0 || x >= BouncingSquares.WIDTH - 24) velX *= -1;
    if(y <= 0 || y >= BouncingSquares.HEIGHT - 47) velY *= -1;

    handler.addObject(new Trail((int)(x), (int)(y), ID.Trail, color, 16, 16, 0.0075f, handler));
}

public void render(Graphics g) {
    g.setColor(color);
    g.fillRect((int)(x), (int)(y), 16, 16);
}

}

The class creates a square of a random color and then it bounces around the window. What I want it to do is fade the values of each color between their minimum and maximum values. I get an error if I un-comment the red/green/blue += red/green/blueVel saying that the color is outside of the expected range.

Is there a way to change the color similar to the way I have the square change directions when it hits the edge of the window?

Edit: I ran the program to find the exception, and it worked. I didn't change anything prior to running it, but I did occasionally get the exception listed below. I think I fixed that by changing the initial random size to 254 and clamping between 1 and 254.

0 个答案:

没有答案