嗨,每次从墙上反弹时如何改变球的颜色?

时间:2017-07-18 09:53:29

标签: java colors

我的球码在这里: 我不知道当他撞到墙壁时如何让球变色。如果我们想在每次从墙上反弹时随机改变颜色,该怎么办?

//Ball.java
import java.awt.Color;             
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;


public class Ball {
private static final int DIAMETER = 30; //diametrul mingii
private static final int RECTANGLE = 30;
private static final int WIDTH = 50;    //Pallet width
private static final int HEIGHT = 50;   //Pallet height 

int x = 0;      //The initial position of the ball, up
int y = 0;      //The initial position of the ball, left
int xa = 1; 
int ya = 1; 

private Game game;
private int score=0;
public Ball(Game game) {
    this.game= game;
}

void move() {
    //Each if limits a border of the window
    if (x + xa < 0)
        xa = 1;     //The ball moves to the right with one pixel each round

    if (x + xa > game.getWidth() - DIAMETER)    //When the ball exceeds the edge, we change direction

        xa = -1;

    if (y + ya < 0)
        ya = 1;     
    if (y + ya > game.getHeight() - DIAMETER)   // When the ball exceeds the bottom edge of the window,

    if (collision()){       //mingea se deplaseaza in sus, daca se intersecteaza cu jucatorul
        ya = -1;                                
        y = game.player.getTopY() - DIAMETER;   //plasam mingea deasupra jucatorului, 
                //For the rectangles they are in, do not intersect

    }
    x = x + xa;     //Make the trips above
    y = y + ya;     
}
private boolean collision() {
    return game.player.getBounds().intersects(getBounds()); //returneaza true daca dreptunghiul  

}

public void paint(Graphics2D g) {
    g.fillOval(x, y, DIAMETER, DIAMETER);
}
public void paintComponent(Graphics g) {   
    g.fillRect(x, y, RECTANGLE, RECTANGLE );
}

    public Rectangle getBounds() {
    return new Rectangle(x, y, DIAMETER, DIAMETER);


    }

  }

我很感激帮助。

2 个答案:

答案 0 :(得分:2)

简单解决方案:添加新布尔值以了解是否存在冲突,例如boolean coll = false。在if (collision())语句中,添加coll = true。然后改变这个:

public void paint(Graphics2D g) {
    g.fillOval(x, y, DIAMETER, DIAMETER);
}

到此:

public void paint(Graphics2D g) {
    if (coll){
        Random r = new Random();
        g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        coll = false;
    }
    g.fillOval(x, y, DIAMETER, DIAMETER);
}

这可能需要你导入随机包,有些东西可能是错的,我不记得了,我现在无法测试,抱歉,但总的来说这就是想法。

答案 1 :(得分:0)

当球接触墙壁时,你需要它来改变你的图形的颜色,根据你的评论,与墙壁的碰撞发生在这里:

if (x + xa > game.getWidth() - DIAMETER)    //When the ball exceeds the edge, we change direction
    xa = -1;

所以你需要做一个额外的动作:

if (x + xa > game.getWidth() - DIAMETER) {   //When the ball exceeds the edge, we change direction
    xa = -1;
    g.setColor(Color.red); //or any other color
}

请注意,您需要将g元素传递到move函数,以便对其进行操作,就像在paint函数中执行操作一样。还有一件事是,您需要将颜色变化线添加到墙壁,地板或天花板的任何碰撞中。至于使颜色随机,您应该能够通过一些努力自己实现它