天天看点

一些好用的方法,编写游戏的时候可能用的上!不断更新中_2009_04_23

1.Bresenham 直线画法 改进版: 

/** *//**  

     * Bresenham Line Algorithm  

     * @param dashedMask 设置线型的虚线的间隔,为0则画实线。  

     * @param lineWidth 设置线宽。  

     * @param x1   

     * @param y1  

     * @param x2  

     * @param y2  

    */ 

    public static void bresenhamLine(Graphics g, int dashedMask, int lineWidth, int x1, int y1, int x2, int y2)   

    ...{  

        g.setColor( 0xFFFFFF );  

        int x, y;  

        int dx, dy;  

        int incx, incy;  

        int balance;  

        int i = 0;  

        if (x2 >= x1)  

        ...{  

            dx = x2 - x1;  

            incx = 1;  

        } else   

            dx = x1 - x2;  

            incx = -1;  

        }  

        if (y2 >= y1)   

            dy = y2 - y1;  

            incy = 1;  

            dy = y1 - y2;  

            incy = -1;  

        x = x1;  

        y = y1;  

        if (dx >= dy)   

            dy <<= 1;  

            balance = dy - dx;  

            dx <<= 1;  

            while (x != x2)   

            ...{  

                if ((i & dashedMask) == 0)  

                    g.fillRect(x, y, lineWidth, lineWidth);  

                if (balance >= 0)   

                ...{  

                    y += incy;  

                    balance -= dx;  

                }  

                balance += dy;  

                x += incx;  

                i++;  

            }  

            if ((i & dashedMask) == 0)  

                g.fillRect(x, y, lineWidth, lineWidth);  

        }   

        else   

            balance = dx - dy;  

            while (y != y2)   

                    x += incx;  

                    balance -= dy;  

                balance += dx;  

                y += incy;  

    } 

2.绘制精灵飞行轨迹方法 

使用示例

isFlyEnd=paintPicFly( g, sprite[y][x], sprite[y][x].getX(), sprite[y][x].getY(), x*RECT_W, y*RECT_H, 4 );

     * 绘制精灵飞行轨迹  

     * @param g  

     * @param sprite  

     * @param x1    起点  

     * @param x2    终点  

     * @param speed 速度  

     * @return        是否飞行结束  

     */ 

    public final boolean paintPicFly( Graphics g, Sprite sprite, int x1, int y1, int x2, int y2, int speed )  

        if( x1==x2 && y1==y2 )  

            sprite.paint(g);  

            return true;  

            for( ; x!=x2; )    //while (x != x2)   

                if ((i & speed) == 0 || i == speed )  

                    paintPic( g, sprite, x, y );  

                    return false;  

            if ((i & speed) == 0 || i == speed )  

                paintPic( g, sprite, x, y );  

            for( ; y!=y2; )    //while (y != y2)   

        return false;  

    }  

    void paintPic( Graphics g, Sprite sprite, int x, int y )  

        sprite.setPosition(x,y);  

        sprite.paint(g);  

//        g.setColor( 0xFF0000 );  

//        g.fillRect(x, y, 1, 1);  

 3.矩形碰撞检测

 /** *//**  

    * 矩形碰撞检测  

    * @param x1    矩形1左上角X坐标  

    * @param y1    矩形1左上角y坐标  

    * @param w1    矩形1宽  

    * @param h1    矩形1高  

    * @param x2    矩形2左上角y坐标  

    * @param y2    矩形2左上角y坐标  

    * @param w2    矩形2宽  

    * @param h2    矩形2高  

    * @return    是否碰撞  

   boolean isIntersect(int x1,int y1, int w1, int h1, int x2, int y2, int w2, int h2)  

   ...{  

       if( Math.abs(x2-x1) < (w1+w2)/2 && Math.abs(y2-y1) < (h1+h2)/2 )  

       ...{  

           return true;  

       }  

       else 

           return false;  

   }  

/以上方法是有问题的!请参看以下方法  

/**  

    * @param x2    矩形2左上角x坐标  

    * @return     是否碰撞  

public static boolean  isIntersect(int x1,int y1, int w1, int h1, int x2, int y2, int w2, int h2)  

   {  

       if( isIntersect(x1,y1,w1,h1,x2   ,y2) )  

       if( isIntersect(x1,y1,w1,h1,x2+w2,y2) )  

       if( isIntersect(x1,y1,w1,h1,x2+w2,y2+h2) )  

       if( isIntersect(x1,y1,w1,h1,x2   ,y2+h2) )  

       return false;  

//判断一个点是否在一个矩形内部或者在这个矩形的边上  

private static boolean isIntersect(int x,int y, int w, int h, int px, int py)  

{  

 if( px>=x&&px<=x+w && py>=y&&py<=y+h )  

  return true;  

 else 

  return false;  

4.单Player播放MIDI

static boolean                            m_isSoundOn;  

    static boolean                            m_isMusicOn;  

    static int                                m_currentSound;  

    static int                                m_currentMIDIID;  

    static javax.microedition.media.Player    m_sound;  

    static byte[][]                         s_soundData;  

    static boolean                             s_isPlayMid = false;  

    void LoadSound()  

        try 

            SetCurrentInputStream( new DataInputStream("".getClass().getResourceAsStream("/sou") ) );  

            ReadOffsetTable();  

            s_soundData = new byte[m_nDataBlocksCount][];  

            byte[] buffer = new byte[ m_dataBlocksOffset[ m_nDataBlocksCount ] ];  

            int[]  header = m_dataBlocksOffset;  

            ReadBytes(buffer);  

            SetCurrentInputStream( null );  

            System.gc();  

            for (int i=0; i<m_nDataBlocksCount; i++)  

                int length = header[ i + 1 ] - header[ i ];  

                if ( length > 0 )  

                    s_soundData[i] = new byte[length];  

                    System.arraycopy( buffer, header[i], s_soundData[i], 0, length );  

            header = null;       

            buffer = null;  

            System.gc();         

            m_currentSound = -1;  

            m_currentMIDIID = -1;  

        catch ( Exception e ) ...{ }  

    static void PlaySound(int id)  

           PlaySoundLoop(id,1);  

    static void PlaySoundLoop( int id, int loop )  

        if (id <= dSoundID.Sound_ID_TITLE)  // midi  

            if (!m_isMusicOn)  

                return;  

        else      // wav  

            if (!m_isSoundOn && id != dSoundID.Sound_ID_MENUCONFIRM)  

        if (id == m_currentSound && m_sound!=null&& (m_sound.getState() == javax.microedition.media.Player.STARTED))  

            return;  

        else 

            StopSound(id);  

        try   

            InputStream is = new ByteArrayInputStream( s_soundData[id] );  

            m_sound = javax.microedition.media.Manager.createPlayer(is, "audio/midi");  

            m_sound.realize();  

            m_sound.setLoopCount( loop );  

            m_sound.start();  

            m_currentSound = id;  

            s_isPlayMid = false;  

        catch (Exception e) ...{ e.printStackTrace(); }  

    static void StopSound(int id)  

            if( m_sound == null )  

            else 

                m_sound.deallocate();  

                m_sound.close();  

                m_sound = null;  

        catch ( Exception e ) ...{ e.printStackTrace(); }  

    static void ResumeSound()  

        PlaySound( m_currentSound );  

5.从一张大图分割成小图

try 

      ...{  

          img        = Image.createImage("/pics/"+imgNum+".png");//将大图创建到临时Image对象中  

          Graphics gn;                                        //创建临时绘图设备  

          for( int i=0; i<y_tile_sum; i++ )  

          ...{  

              for( int j=0; j<x_tile_sum; j++ )  

              ...{  

                  img_tile[i][j] = Image.createImage(RECT_W, RECT_H);            //创建小图的大小  

                  gn = img_tile[i][j].getGraphics();                            //创建小图的大小的临时绘图设备      

                  //在该设备上绘制大图temp,但 绘图设备比较小,只有小图那么大,大图多余部分不会被绘制出来  

                  gn.drawImage(img, -j*RECT_W, -i*RECT_H, gn.LEFT|gn.TOP);    //绘制大图时候的起点位置  

              }  

          }  

          gn     = null;  

          System.gc();    //通知垃圾回收机制,在需要时候会进行垃圾回收  

      }  

      catch(Exception e)...{ e.printStackTrace(); } 

6.j2me 保存记录

final static String RECORD_FILENAME = "/assassin.sav";  

    final static int RECORD_SIZE = 160;  

    static byte s_recordData[] = new byte[RECORD_SIZE];  

    public static void RecordStore(boolean save)  

            RecordStore rs = RecordStore.openRecordStore(RECORD_FILENAME, true);  

            if (rs.getNumRecords() <= 0)  

                if (save)  

                    rs.addRecord(s_recordData, 0, RECORD_SIZE);  

                else 

                    rs.closeRecordStore();  

                    return;  

            else if (save)  

                rs.setRecord(1, s_recordData, 0, RECORD_SIZE);  

                rs.getRecord(1, s_recordData, 0);  

            rs.closeRecordStore();  

            rs = null;  

        catch (Exception e)  

本文转自 kome2000 51CTO博客,原文链接:http://blog.51cto.com/kome2000/578525