在此之後詢問新問題,發現here。如何在同一時間滾動多個對象?
我是Java的新手,但我正在研究「Flappy Bird」的娛樂活動,以瞭解更多關於java和圖形顯示方式的信息。對我的任何問題的任何解決方案或建議非常感謝。謝謝!
現在,我的程序使得隨機管和滾動,但我並不需要它來保持滾動時x1-3 = -83
(這是當管會完全關閉屏幕,並且不再需要) 。
問題
我怎樣才能讓我的Game.class
滾動Pipes.class
多個實例,同時增加它們之間的預設距離?我可以找出他們之間的距離,但就展示不止一個,我不知道該怎麼做。最多3個管道必須同時顯示。
如何顯示主菜單的面板,然後在按下啓動按鈕後切換到管道面板?
類
Game.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Game {
Pipes panel = new Pipes();
public Game() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
f.setTitle("Pipe Game");
f.setResizable(false);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Timer timer = new Timer(10, new ActionListener() { //pipe speed
@Override
public void actionPerformed(ActionEvent e) {
panel.move();
}
});
timer.start();
Timer refresh = new Timer(30, new ActionListener() { //refresh rate
@Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
refresh.start();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Game();
}
});
}
}
Pipes.java
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Pipes extends JPanel {
//Declare and initialiaze variables
int x1 = 754; //xVal start
int x2 = 75; //pipe width
//total width is 83
int y1 = -1; //yVal start
int y2 = setHeightVal(); //pipe height
int gap = 130; //gap height
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0,0,750,500); //Clear screen
g.drawRect(x1,y1,x2,y2); //Draw part 1
g.drawRect(x1-3,y2-1,x2+6,25); //Draw part 2
g.drawRect(x1-3,y2+25+gap,x2+6,25); //Draw part 3
g.drawRect(x1,y2+25+gap+25,x2,500-y2-49-gap); //Draw part 4
}
public void move() {
x1--;
}
public int getMyX() { //To determine where the pipe is horizontally
return x1-3;
}
public int getMyY() { //To determine where the pipe is vertically
return y2+25;
}
public int setHeightVal() { //Get a random number and select a preset height
int num = (int)(9*Math.random() + 1);
int val = 0;
if (num == 9)
{
val = 295;
}
else if (num == 8)
{
val = 246;
}
else if (num == 7)
{
val = 216;
}
else if (num == 6)
{
val = 185;
}
else if (num == 5)
{
val = 156;
}
else if (num == 4)
{
val = 125;
}
else if (num == 3)
{
val = 96;
}
else if (num == 2)
{
val = 66;
}
else
{
val = 25;
}
return val;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(751, 501);
}
}
Timer timer = new Timer(10,new ActionListener(){很短的延遲,必須使用23-30作爲最小刷新頻率, – mKorbel
謝謝,我會改變這種情況。只是好奇,爲什麼我的刷新率是什麼?什麼是最佳的,這樣我就不會閃爍,管道平穩地移動? –
另外,這個數字不僅僅是我的刷新率,它決定了在移動管道之前需要等待多長時間,所以它還可以控制管道的速度。 –