使用GameCanvas制作星空效果

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

MIDP2.0中提供了游戏开发专用的API,比如GameCanvas等类。他们位于Javax.microedition.lcdui.game包内。本文介绍GameCanvas的基本使用方法并实现一种滚动星空的效果。您可以参考Game Canvas Basic获得更具体的信息。

GameCanvas是Canvas的子类,因此他同样继续了Canvas类的一些特性,比如showNotify()方法会在Canvas被显示在屏幕的时候调用,而hideNotify()会在Canvas离开屏幕的时候被调用。我们可以把他们当作监听器来使用,用于初始化和销毁资源。比如

// When the canvas is shown, start a thread to

// run the game loop.

protected void showNotify()

{

random = new Random();

thread = new Thread(this);

thread.start();

}

// When the game canvas is hidden, stop the thread.

protected void hideNotify()

{

thread = null;

}

在游戏开发中最重要的就是接受用户触发的事件然后重新绘制屏幕,通常我们使用getKeyStates()方法判定哪个键被按下了,然后绘制屏幕,调用flushGraphics()。在GameCanvas中,系统事实上已经为我们实现了双缓冲技术,因此每次我们绘制的时候就是在off-screen上绘制的。结束后通过flushGraphics把它复制到屏幕上去。下面是典型的接受事件、处理逻辑、绘制屏幕的代码。

// Get the Graphics object for the off-screen buffer

Graphics g = getGraphics();

while (true) {

// Check user input and update positions if necessary

int keyState = getKeyStates();

if ((keyState & LEFT_PRESSED) != 0) {

sprite.move(-1, 0);

}

else if ((keyState & RIGHT_PRESSED) != 0) {

sprite.move(1, 0);

}

// Clear the background to white

g.setColor(0xFFFFFF);

g.fillRect(0,0,getWidth(), getHeight());

// Draw the Sprite

sprite.paint(g);

// Flush the off-screen buffer

flushGraphics();

}

下面开始实现我们滚动星空的效果,其实设计的思想非常简单。我们启动一个线程,使用copyArea()方法把屏幕的内容往下复制一个像素的距离。然后绘画第一个空白的直线,随机的在直线上绘画点儿,这样看起来就像星空一样了。逻辑代码如下:

// The game loop.

public void run()

{

int w = getWidth();

int h = getHeight() - 1;

while (thread == Thread.currentThread())

{

// Increment or decrement the scrolling interval

// based on key presses

int state = getKeyStates();

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航