java遊戲-碰到矩形邊界時反彈-swing介面

來源:互聯網
上載者:User

 

import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.image.BufferedImage;public class Hufan extends JFrame{static HuPanel hp;static Hufan hu;public static void main(String[] args) {hu=new Hufan();}public Hufan(){hp=new HuPanel();this.addKeyListener(hp);this.add(hp);this.setSize(500, 400);this.setLocation(400, 300);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}}class HuPanel extends JPanel implements KeyListener{Rect rect;HuRect huRect;public HuPanel(){rect=new Rect(20,40);huRect=new HuRect(180,290);Thread t=new Thread(rect);t.start();}public void paint(Graphics g){super.paint(g);g.drawRect(0, 0, 400, 300);g.setColor(Color.red);g.fillRect(rect.x, rect.y, 20,20);g.setColor(Color.blue);g.fillRect(huRect.x, huRect.y, 80, 10);}@Overridepublic void keyPressed(KeyEvent e) {switch(e.getKeyCode()){case KeyEvent.VK_LEFT:if(huRect.x>0){huRect.x-=huRect.speed;}break;case KeyEvent.VK_RIGHT:if(huRect.x<320){huRect.x+=huRect.speed;}break;}this.repaint();}public void keyReleased(KeyEvent arg0) {}public void keyTyped(KeyEvent arg0) {}}class Rect implements Runnable{//方塊類int x;int y;int speedX=3;//x軸移動速度int speedY=3;//y軸移動速度boolean kaiGuan=true;public Rect(int x,int y){this.x=x;this.y=y;}public void run() {while(this.kaiGuan){x=x+speedX;y=y+speedY;if(x<=0||x>=380){speedX=-speedX;//到達左右邊界時,x軸移動速度取反}if(y<=0){speedY=-speedY;//到達左右邊界時,y軸移動速度取反}if(y>=280){this.kaiGuan=false;}int xx=Hufan.hp.huRect.x;int yy=Hufan.hp.huRect.y;if(x>=xx&&x<=xx+80&&y+20>=yy&&y+20<=yy+10){//方塊與矩形相碰檢測speedY=-speedY;}try {Thread.sleep(30);} catch (InterruptedException e) {e.printStackTrace();}Hufan.hu.hp.repaint();}}}class HuRect extends Rect{//下面的矩形類int speed=5;public HuRect(int x, int y) {super(x, y);}}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.