| |
一步一步学习midp2。0游戏编程(五) sprite(精灵类) sprite是用个用来显示图像的类 (每次一个). 该类和tiledlayer的区别是。sprite是由一个图像(可以有好几帧,但是一次只有一个显示)组成 (当然sprite还有其他的额外特性,不过每次只能只用一个图像而不是一次使用多个图像来填充屏幕是它的最主要特征.) 因而sprite 被用来定义一些小的有动作的游戏对象(比如飞船和小行星对撞), tiledlayer 更被常用来构造生动的背景. sprite另一个让人激动的特性是:虽然它一次只能显示一个图像,但是我们可以为它定义一系列的图像,以便在不同的环境下构造不同的动画. 在我的例子中,牛仔有三帧图像描绘它的走路,一帧描绘牛仔的跳. 这些将要赋值给sprite的图像需要被存在一个png文件中.这些帧被存在一个文件中的好处是你可以从管理多个image对象的麻烦中解脱出来。下面是牛仔类的图片:  这个是滚草的动画:  在某个特定的时刻决定显示哪一帧帧是非常直观的. 第一, 如果你的图像文件包括多个帧, 在构造sprite 类的时候你需要指定精灵的高度和宽度(象素值). 图像的高度和宽度必须是精灵高宽的整数倍.换句话说,你要能正好让电脑把你的图像按照精灵的大小划分成几个类. 通过上面的例子你也看到了,至于这些帧是横着拍还是竖着排抑或横竖都有排成一个方阵都无所谓. 接着就可以指定帧数了, 左上放是编号0,然后从左到右,从上到下依次排列。你可以使用setframe(int sequenceindex) 选择哪一帧被显示,是要把它的编号作为参数传递就成了.
sprite还可以让你使用方法setframesequence(int[] sequence)定义一个帧的序列.比如我可以为牛仔定义这么一个序列 { 1, 2, 3, 2 }而为滚草定义 { 0, 1, 2 } 序列. 使用nextframe(),就可以让你的sprite 动画前进了。(后退的话使用prevframe()).对于象滚草这样使用了全部帧的情况的确很方便,不过对于象牛仔这样有的帧没有使用的情况就稍微有点复杂了。这是因为一个序列一旦被设置, setframe(int sequenceindex) 方法中的参数对应的帧数变成了序列数组中对应的参数而不是图片本身参数的顺序。比如我把牛仔的序列设置为 { 1, 2, 3, 2 },如果我调用setframe(0)的话,序号为1的那帧被显示, setframe(3)将会显示2. 因而如果让人物跳起的动画对应的第0帧就没有办法引用了.所以当我需要牛仔跳起时,我需要设置序列为null,然后再调用setframe(0),接着再把序列设置成 { 1, 2, 3, 2 }. 你可以参考下面代码中的jump() 和 advance(int tickcount, boolean left). 当帧改变时,为了改变精灵的外观,你可对它去旋转或者镜像的操作. 牛仔和滚草都可以向左或者向右运动,所以我需要对图像进行镜像变换以得到相反方向的动作. 当你开始变换成,你需要保留住精灵的引用象素. 这是因为如果你变换你的精灵的时候, 引用象素是一个不变的象素. 你可以设想,你的精灵图像是一个矩形,当它进行变换以后,仍然是原来位置上的那个矩形。这是不一定的。为了说明.我们来设想一个例子,有一个向左站的人,他的引用象素在脚趾上对他进行90度旋转以后, 你会发现他向前倒在地上了.很明显是引用象素发生了作用 (好像一个图钉).如果你希望变换后仍然占有相同的矩形话,你需要首先调用 definereferencepixel(int x, int y) 把你的精灵的引用象素设置成矩形的中心, 就想我在下面代码的构造方法中干的那样. 要注意 definereferencepixel(int x, int y)中的坐标 是相对于精灵的左上角,然而setrefpixelposition(int x, int y)使用的是整个屏幕的坐标系统. 更准确的说,被送到 setrefpixelposition(int x, int y)中的坐标用的是精灵将被直接绘制到的canvas的坐标系统, 但是如果精灵通过 layermanager进行绘制, 那么使用的就是layermanager的坐标系统了. (这些坐标的关系在在 layermanager那部分已经讲解过了) 要特别注意的是,如果你对一个精灵图像进行了多重变化的话,后面的变化是相对原始状态而不是当前状态. 换句话说,如果你调用了两次 settransform(trans_mirror)和调用一次的效果是一样的,而不是想你想象的那样再变换回去. 如果你想让你的变型还原,调用settransform(trans_none). 在 cowboy.advance(int tickcount, boolean left) 中有具体演示. layer(包括sprites tiledlayers) 类的另外一个灵光人激动的特性就是可以让你把你的对象放置到一个对象之间相互关联的体系中而不是一个彼此没有联系的绝对体系. 如果你想让你的精灵sprite 移动3个象素而不管它现在所处的环境的话, 你可以调用move(int x, int y) ,其中x,y分别代表这两个方向上的偏移量, 而不像 setrefpixelposition(int x, int y)那样使用绝对坐标来定义精灵的新的位置. collideswith()也是非常有用.他可以检测一个精灵是否和另外一个精灵或者tiledlayers 或者一个image发生碰撞. 特别是如果你把pixellevel参数设置成true的话,他会检测是不是两个不透明发生碰撞,而如果仅仅这两者的透明发生碰撞就被忽略。 在 "tumbleweed" 游戏中, 让所有的sprites播放后,我会检查牛仔是不是和滚草发生了碰撞. (具体检测在 cowboy.checkcollision(tumbleweed tumbleweed)方法中,jumpmanager.advance(int gameticks)会调用它)。我会检查牛仔所有滚草之间的碰撞,除了那些不可见的滚草,因为它们肯定会返回false. 在我的例子中,为了省点力气 你可以只检测那些有可能发生碰撞的物体而不是所有的物体两两之间都要检测。你可以注意到,在我的例子中我没有检测滚草之间的碰撞以及背景草皮的碰撞,因为那些碰撞和游戏的逻辑不太相关。如果你在检查一个象素级别的碰撞,你得确认你的图片有透明背景. (透明是很重要的,它让你可以在绘制图片的时候不必把那个那个丑陋的带有背景颜色的矩形也画出来)至于 怎么正确的创建图片参见附录 b. 这是 cowboy.java的代码: package net.frog_parrot.jump; import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.*; /** * this class represents the player. * * @author carol hamer */ public class cowboy extends sprite { //--------------------------------------------------------- // dimension fields /** * the width of the cowboy's bounding rectangle. */ static int width = 32; /** * the height of the cowboy's bounding rectangle. */ static int height = 48; /** * this is the order that the frames should be displayed * for the animation. */ static int[] frame_sequence = { 3, 2, 1, 2 }; //--------------------------------------------------------- // instance fields /** * the x coordinate of the cowboy where the cowboy starts * the game. */ int myinitialx; /** * the y coordinate of the cowboy when not jumping. */ int myinitialy; /** * the jump index that indicates that no jump is * currently in progress.. */ int mynojumpint = -6; /** * where the cowboy is in the jump sequence. */ int myisjumping = mynojumpint; /** * if the cowboy is currently jumping, this keeps track * of how many points have been scored so far during * the jump. this helps the calculation of bonus points since * the points being scored depend on how many tumbleweeds * are jumped in a single jump. */ int myscorethisjump = 0; //--------------------------------------------------------- // initialization /** * constructor initializes the image and animation. */ public cowboy(int initialx, int initialy) throws exception { super(image.createimage("/icons/cowboy.png"), width, height); myinitialx = initialx; myinitialy = initialy; // we define the reference pixel to be in the middle // of the cowboy image so that when the cowboy turns // from right to left (and vice versa) he does not // appear to move to a different location. definereferencepixel(width/2, 0); setrefpixelposition(myinitialx, myinitialy); setframesequence(frame_sequence); } //--------------------------------------------------------- // game methods /** * if the cowboy has landed on a tumbleweed, we decrease * the score. */ int checkcollision(tumbleweed tumbleweed) { int retval = 0; if(collideswith(tumbleweed, true)) { retval = 1; // once the cowboy has collided with the tumbleweed, // that tumbleweed is done for now, so we call reset // which makes it invisible and ready to be reused. tumbleweed.reset(); } return(retval); } /** * set the cowboy back to its initial position. */ void reset() { myisjumping = mynojumpint; setrefpixelposition(myinitialx, myinitialy); setframesequence(frame_sequence); myscorethisjump = 0; // at first the cowboy faces right: settransform(trans_none); } //--------------------------------------------------------- // graphics /** * alter the cowboy image appropriately for this frame.. */ void advance(int tickcount, boolean left) { if(left) { // use the mirror image of the cowboy graphic when // the cowboy is going towards the left. settransform(trans_mirror); move(-1, 0); } else { // use the (normal, untransformed) image of the cowboy // graphic when the cowboy is going towards the right. settransform(trans_none); move(1, 0); } // this section advances the animation: // every third time through the loop, the cowboy // image is changed to the next image in the walking // animation sequence: if(tickcount % 3 == 0) { // slow the animation down a little if(myisjumping == mynojumpint) { // if he's not jumping, set the image to the next // frame in the walking animation: nextframe(); } else { // if he's jumping, advance the jump: // the jump continues for several passes through // the main game loop, and myisjumping keeps track // of where we are in the jump: myisjumping++; if(myisjumping < 0) { // myisjumping starts negative, and while it's // still negative, the cowboy is going up. // here we use a shift to make the cowboy go up a // lot in the beginning of the jump, and ascend // more and more slowly as he reaches his highest // position: setrefpixelposition(getrefpixelx(), getrefpixely() - (2 << (-myisjumping))); } else { // once myisjumping is negative, the cowboy starts // going back down until he reaches the end of the // jump sequence: if(myisjumping != -mynojumpint - 1) { setrefpixelposition(getrefpixelx(), getrefpixely() + (2 << myisjumping)); } else { // once the jump is done, we reset the cowboy to // his non-jumping position: myisjumping = mynojumpint; setrefpixelposition(getrefpixelx(), myinitialy); // we set the image back to being the walking // animation sequence rather than the jumping image: setframesequence(frame_sequence); // myscorethisjump keeps track of how many points // were scored during the current jump (to keep // track of the bonus points earned for jumping // multiple tumbleweeds). once the current jump is done, // we set it back to zero. myscorethisjump = 0; } } } } } /** * makes the cowboy jump. */ void jump() { if(myisjumping == mynojumpint) { myisjumping++; // switch the cowboy to use the jumping image // rather than the walking animation images: setframesequence(null); setframe(0); } } /** * this is called whenever the cowboy clears a tumbleweed * so that more points are scored when more tumbleweeds * are cleared in a single jump. */ int increasescorethisjump() { if(myscorethisjump == 0) { myscorethisjump++; } else { myscorethisjump *= 2; } return(myscorethisjump); } } 下面是tumbleweed.java的代码: package net.frog_parrot.jump; import java.util.random; import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.*; /** * this class represents the tumbleweeds that the player * must jump over. * * @author carol hamer */ public class tumbleweed extends sprite { //--------------------------------------------------------- // dimension fields /** * the width of the tumbleweed's bounding square. */ static int width = 16; //--------------------------------------------------------- // instance fields /** * random number generator to randomly decide when to appear. */ random myrandom = new random(); /** * whether or not this tumbleweed has been jumped over. * this is used to calculate the score. */ boolean myjumpedover; /** * whether or not this tumbleweed enters from the left. */ boolean myleft; /** * the y coordinate of the tumbleweed. */ int myy; //--------------------------------------------------------- // initialization /** * constructor initializes the image and animation. * @param left whether or not this tumbleweed enters from the left. */ public tumbleweed(boolean left) throws exception { super(image.createimage("/icons/tumbleweed.png"), width, width); myy = jumpmanager.disp_height - width - 2; myleft = left; if(!myleft) { settransform(trans_mirror); } myjumpedover = false; setvisible(false); } //--------------------------------------------------------- // graphics /** * move the tumbleweed back to its initial (inactive) state. */ void reset() { setvisible(false); myjumpedover = false; } /** * alter the tumbleweed image appropriately for this frame.. * @param left whether or not the player is moving left * @return how much the score should change by after this * advance. */ int advance(cowboy cowboy, int tickcount, boolean left, int currentleftbound, int currentrightbound) { int retval = 0; // if the tumbleweed goes outside of the display // region, set it to invisible since it is // no longer in use. if((getrefpixelx() + width <= currentleftbound) || (getrefpixelx() - width >= currentrightbound)) { setvisible(false); } // if the tumbleweed is no longer in use (i.e. invisible) // it is given a 1 in 100 chance (per game loop) // of coming back into play: if(!isvisible()) { int rand = getrandomint(100); if(rand == 3) { // when the tumbleweed comes back into play, // we reset the values to what they should // be in the active state: myjumpedover = false; setvisible(true); // set the tumbleweed's position to the point // where it just barely appears on the screen // to that it can start approaching the cowboy: if(myleft) { setrefpixelposition(currentrightbound, myy); move(-1, 0); } else { setrefpixelposition(currentleftbound, myy); move(1, 0); } } } else { // when the tumbleweed is active, we advance the // rolling animation to the next frame and then // move the tumbleweed in the right direction across // the screen. if(tickcount % 2 == 0) { // slow the animation down a little nextframe(); } if(myleft) { move(-3, 0); // if the cowboy just passed the tumbleweed // (without colliding with it) we increase the // cowboy's score and set myjumpedover to true // so that no further points will be awarded // for this tumbleweed until it goes offscreen // and then is later reactivated: if((! myjumpedover) && (getrefpixelx() < cowboy.getrefpixelx())) { myjumpedover = true; retval = cowboy.increasescorethisjump(); } } else { move(3, 0); if((! myjumpedover) && (getrefpixelx() > cowboy.getrefpixelx() + cowboy.width)) { myjumpedover = true; retval = cowboy.increasescorethisjump(); } } } return(retval); } /** * gets a random int between * zero and the param upper. */ public int getrandomint(int upper) { int retval = myrandom.nextint() % upper; if(retval < 0) { retval += upper; } return(retval); } } tiledlayer 类 前面已经说过了, tiledlayer 和sprite是非常类似的,除了tiledlayer 可以由一些重复的图像单元拼接而成. 两者之间的另外一个区别就是tiledlayer不能变型,引用象素,或者使用一系列图片中的一帧. 常识告诉我们,同时管理这么多的图像会使事情变得稍微复杂一些. 我将结合名为grass的 tiledlayer类来进行讲解. 这个类实现了游戏进行时让背景上的草前后摆动的功能. 为了让这个例子有趣一些,我定义了两种背景,一个是可以摇摆的草,另一个是底层固定不变的绿色背景. 摇摆的草的图像如下: 注意: sprite的编号是从0开始的, 但是 tiledlayer却是从1开始的 (我一开始因为没注意的问题得到了个indexoutofboundsexception 异常).在tiledlayer中,序号0表示一个空白的元素 (比如在某个位置你什么都不想画,那就把他设置成0). sprite只有一个单元组成, 所以如果你向让它不显示这个单元,简单的设置成 setvisible(false)就可以了, 因而sprite不需要一个特殊的编号来表示空白的单元. 序号的不一致应该不是什么大问题,不过如果你的动画显示不正确,我到建议你查查是不是序号用错了.
创建 tiledlayer的第一步是决定你需要定义几行几列. 如果你不希望的层被定义成一个矩形也是有办法 ,所有不用的单元会默认的设置为空白.在我的例子中,我把行数定义为1,并且根据屏幕的宽度计算列数. 一旦你定义了行列的规模,你就可以使用 setcell(int col, int row, int tileindex)来定义任何一个单元的内容了. tileindex 参数在sprite 部分已经讲过了,并且上文我用了一段来说明两个类中index的区别. 如果你希望某个元素有动画效果,你需要使用 createanimatedtile(int statictileindex)来定义一个动画元素, 这个方法将会返回一个分配给你的那个动画元素的编号. 你可以创建足够多的动画元素,但是如果你需要在屏幕上同时显示它们的时候,请保证它们都可用. 在我的例子中,我就创建了一个动画元素,我在例子中重复使用它们,因为我希望这些草同步舞动. 为了播放动画,你不需要想sprite那样得到内置的帧序列,你只要使用setanimatedtile(int animatedtileindex, int statictileindex)方法就可以了. 这个方法为指定的元素设置当前帧,因而所有包含这个动画元素的单元的当前帧会随之变成刚刚指定的帧。参看一下grass.advance(int tickcount)方法的代码,你会更好的掌握 这是我们最后一个类了, grass.java: package net.frog_parrot.jump; import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.*; /** * this class draws the background grass. * * @author carol hamer */ public class grass extends tiledlayer { //--------------------------------------------------------- // dimension fields // (constant after initialization) /** * the width of the square tiles that make up this layer.. */ static int tile_width = 20; /** * this is the order that the frames should be displayed * for the animation. */ static int[] frame_sequence = { 2, 3, 2, 4 }; /** * this gives the number of squares of grass to put along * the bottom of the screen. */ static int columns; /** * after how many tiles does the background repeat. */ static int cycle = 5; /** * the fixed y coordinate of the strip of grass. */ static int top_y; //--------------------------------------------------------- // instance fields /** * which tile we are currently on in the frame sequence. */ int mysequenceindex = 0; /** * the index to use in the static tiles array to get the * animated tile.. */ int myanimatedtileindex; //--------------------------------------------------------- // gets / sets /** * takes the width of the screen and sets my columns * to the correct corresponding number */ static int setcolumns(int screenwidth) { columns = ((screenwidth / 20) + 1)*3; return(columns); } //--------------------------------------------------------- // initialization /** * constructor initializes the image and animation. */ public grass() throws exception { super(setcolumns(jumpcanvas.disp_width), 1, image.createimage("/icons/grass.png"), tile_width, tile_width); top_y = jumpmanager.disp_height - tile_width; setposition(0, top_y); myanimatedtileindex = createanimatedtile(2); for(int i = 0; i < columns; i++) { if((i % cycle == 0) || (i % cycle == 2)) { setcell(i, 0, myanimatedtileindex); } else { setcell(i, 0, 1); } } } //--------------------------------------------------------- // graphics /** * sets the grass back to its initial position.. */ void reset() { setposition(-(tile_width*cycle), top_y); mysequenceindex = 0; setanimatedtile(myanimatedtileindex, frame_sequence[mysequenceindex]); } /** * alter the background image appropriately for this frame.. */ void advance(int tickcount) { if(tickcount % 2 == 0) { // slow the animation down a little mysequenceindex++; mysequenceindex %= 4; setanimatedtile(myanimatedtileindex, frame_sequence[mysequenceindex]); } } } 打包 (译者:从这往下的内容对大部分读者不太实用,大阿家参考吧) 当我们拥有了所有需要的类后我们就需要编译它了,方法和前面提到的 "hello world" 例子一样. 这些类需要编译,预处理,打包. (预处理是一个使字节码更容易被虚拟机【原文说是j2me application】确认的额外步骤,不过你不要要过多的担心这个,因为一般的工具都会自动帮你处理这步) 要确定所有的资源文件被放置到jar包中正确的位置. 这个例子中,我需要把cowboy.png, tumbleweed.png, and grass.png i放到一个名为icons的顶层目录中,以便我使用类似下面的这行代码来调用它们 image.createimage("/icons/grass.png"). 另外还必须放置把manifest.mf文件放到正确的位置: midlet-1: hello world, /icons/hello.png, net.frog_parrot.hello.hello midlet-2: tumbleweed, /icons/boot.png, net.frog_parrot.jump.jump mmidlet-description: example games for midp midlet-name: example games midlet-permissions: midlet-vendor: frog-parrot.net midlet-version: 2.0 microedition-configuration: cldc-1.0 microedition-profile: midp-2.0 如果你想使用你自定义的 manifest.mf代替自动生成的文件,在使用jar命令的时候要把加上m选项. 另外你还需要一个jad文件,jump.jad是一个例子: midlet-1: hello, /icons/hello.png, net.frog_parrot.hello.hello midlet-2: tumbleweed, /icons/boot.png, net.frog_parrot.jump.jump mmidlet-description: example games for midp midlet-jar-url: jump.jar midlet-name: example games midlet-permissions: midlet-vendor: frog-parrot.net midlet-version: 2.0 microedition-configuration: cldc-1.0 microedition-profile: midp-2.0 midlet-jar-size: 17259 don't forget to verify that the midlet-jar-size is correct if you're creating the jad file by hand. also note that this jad file indicates that your jar file needs to contain the icon /icons/boot.png which is used in the game selection menu and looks like this: 当 jar 和 jad 都准备好了, 你就可以运行程序了. 我是使用wtk2自带的runmidlet 的脚本来运行的.
好运!
|
|