基于Java的動畫編程基礎第一部分
|
基本技術:
在Java中實現動畫有很多種辦法,但它們實現的基本原理是一樣的,即在屏幕上畫出一系列的幀來造成運動的感覺。
我們先構造一個程序的框架,再慢慢擴展,使之功能比較齊備。
使用線程:
為了每秒中多次更新屏幕,必須創建一個線程來實現動畫的循環,這個循環要跟蹤當前幀并響應周期性的屏幕更新要求。實現線程的方法有兩種,你可以創建一個類Thread的派生類,或附和在一個Runnable的界面上。
一個容易犯的錯誤是將動畫循環放在paint()中,這樣占據了主AWT線程,而主線程將負責所有的繪圖和事件處理。
一個框架applet如下:
| public class Animator1 extends java.applet.Applet implements Runnable { int frame; int delay; Thread animator; public void init() { String str = getParameter("fps"); int fps = (str != null) ? Integer.parseInt(str) : 10; delay = (fps > 0) ? (1000 / fps) : 100; } public vois start() { animator = new Thread(this); animator.start(); } public void run() { while (Thread.currentThread() == animator) { repaint(); try { Thread.sleep(delay); } catch (InterruptedException e) { break; } frame++; } } public void stop() { animator = null; } } |
在你的HTML文件中這樣引用:
| <applet code=Animator1.class width=200 height=200> <param name=fps value=200> </applet> |
上面的參數fps表示每秒的幀數
保持恒定的幀速度:
上例中,applet只是在每兩幀之間休眠一個固定的時間,但這有些缺點,有時你會等很長時間,為了每秒顯示十幀圖象,不應該休眠100毫秒,因為在運行當中也耗費了時間。
這里有一個簡單的補救方法:
| public void run() { long tm = System.currentTimeMillis(); while (Thread.currentThread() == animator) { repaint(); try { tm += delay; Thread.sleep(Math.max(0,tm - System.currentTimeMillis())); } catch (InterruptedException e) { break; } frame++; } } |