2015-12-30 67 views
-2

所以我在這裏有一小段代碼。什麼代碼是應該做的:加速不會加上

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

@SuppressWarnings("serial") 
public class squareMovingUsingArrowKeys extends JPanel implements ActionListener,KeyListener { 
static int x; 
static int y; 
static double acceleration=0.3; 
static int originSpeed; 
static int actualSpeed; 
static boolean a=false; 
Timer timer; 
squareMovingUsingArrowKeys() { 
    x = 0; 
    y = 0; 
    acceleration = 0.3; 
    actualSpeed = 1; 
} 
@SuppressWarnings("deprecation") 
public void keyPressed(KeyEvent e) { 
    a = true; 
    System.out.println(actualSpeed); 
    actualSpeed+=acceleration; 
    if (e.getKeyCode() == KeyEvent.VK_LEFT) { 
     x -= actualSpeed; 
    } 
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) { 
     x += actualSpeed; 
    } 
    if (e.getKeyCode() == KeyEvent.VK_UP) { 
     y -= actualSpeed; 
    } 
    if (e.getKeyCode() == KeyEvent.VK_DOWN) { 
     y += actualSpeed; 
    } 
    //first call move to update x and y and later repaint that JPanel 
    move(x, y); 
    repaint(); 
} 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(new Color(125,125,255)); 
    g.fillRect(x, y, 20, 20); 
    g.setColor(new Color(100,255,100)); 
    g.fillOval(x, y, 20, 20); 
    if(x>=500){ 
     x=500; 
    }else if(y>=500){ 
     y=500; 
    }else if(x<=0){ 
     x=0; 
    }else if(y<=0){ 
     y=0; 
    } 
} 
public void start() { 
    keyPressed(null); 
    paintComponent(null); 
} 
public static void main(String[] args) { 
    JFrame f = new JFrame("Moving"); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    squareMovingUsingArrowKeys m = new squareMovingUsingArrowKeys(); 
    f.add(m); 
    f.setSize(500, 500); 
    f.setVisible(true); 
    f.addKeyListener(m); 
} 
@Override 
public void actionPerformed(ActionEvent e) { 
    // TODO Auto-generated method stub 
} 

public void keyReleased(KeyEvent arg0) { 
    // TODO Auto-generated method stub 
    originSpeed = 1; 
} 
@Override 
public void keyTyped(KeyEvent arg0) { 
    // TODO Auto-generated method stub 
} 
} 

- 能夠「加快」爲你按住一個按鈕

  • 停止當x或y是在500

  • 移動次要方向

但顯然,它不起作用。

我該如何解決這個問題?

+0

停下來是什麼意思?停止加速?你是什​​麼意思的次要方向? – Sneh

+0

完全停止,次要方向是對角線方向。 – bleh

+0

什麼意思是「不起作用」?不工作表現本身如何? – sisyphus

回答

2

你的actualSpeed變量是一個int,你試圖給它加0.3,它是一個double和小於1.如果它大於1,比如說1.2,那麼java會爲你的actualSpeed加1。

更改actualSpeed的類型爲double,它將工作,因爲您無法將雙精度浮點數或浮點數添加到int。

我還會推薦你閱讀Java的原始數據類型。

用於在x = 500或y = 500時停止。您需要在您的密鑰處理程序中使用if語句,該語句檢查x & y =小於500,否則它不會加速。對於移動對角線。你的綠點在我的系統上對角移動。

+0

哎呀,我沒有聽到!關於#2和3呢? – bleh

+0

Like,actualSpeed = 0對於x或y是500 – bleh

+0

我不確定你是問這個還是告訴我這麼做。但主要是它的基本if語句。當你增加加速度時,添加一個額外的if語句來檢查x和y是否小於500,如果是,那麼加速其他操作,然後做任何你想做的事情。 – Sneh