格式化

廣告

廣告2

2012年12月15日 星期六

[JAVA教學範例] awt雙衝緩衝繪製遊戲畫面的範例

[JAVA教學範例] awt雙衝緩衝繪製遊戲畫面的範例



利用雙重緩衝來繪製遊戲的範例
畫個球然後碰到視窗邊會反彈

import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;

import javax.swing.ImageIcon;

public class Window extends MyCanvas {

 private int x, y;
 private int xSpeed, ySpeed;
 private Image ballTexture;

 Window() {
  ballTexture = new ImageIcon("chrome.png").getImage();
  x = new Random().nextInt(690 - ballTexture.getWidth(this));
  y = new Random().nextInt(580 - ballTexture.getHeight(this));
  xSpeed = 3;
  ySpeed = 4;
 }

 @Override
 public void draw(Graphics g) {

  g.drawImage(ballTexture, x, y, null);
 }

 @Override
 public void updates(Graphics g) {

  if (x >= (700 - 8) - ballTexture.getWidth(null))
   xSpeed *= -1;
  if (x <= 0)
   xSpeed *= -1;
  if (y >= (600 - 30) - ballTexture.getHeight(null))
   ySpeed *= -1;
  if (y <= 0)
   ySpeed *= -1;
  x += xSpeed;
  y += ySpeed;
 }
}


沒有留言 :