我的球代碼在這裏: 我不知道如何讓球在撞到牆上時變色。如果我們想每次從牆上彈起時隨機更改球的顏色,該怎麼辦?嗨,如何改變球的顏色每次從牆上反彈?
//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);
}
}
我很感激幫助。
實現,那將是一個很大的幫助,如果您的評論是用英文 – Hatik
這看起來像功課......看看到您的碰撞無論如何功能 – IsThisJavascript
您可以使用'g.setColor'來更改顏色。 – talex