Step by Step,用JAVA做一個FLAPPYBIRD遊戲(四)

遊戲主角——小鳥的實現

這一篇我們講FlappyBird的主角小鳥的實現,下面先給出完整的代碼,然後我們再來講解細節(^_^)

public class Bird {

    private Image[] IMG_BIRD = {
        new ImageIcon("images/bird1.png").getImage(),
        new ImageIcon("images/bird2.png").getImage(),
        new ImageIcon("images/bird3.png").getImage(),
   };
    private int currentFrame=0;
    private int speed = 10;
    public int x = MyGame.gameW/2-IMG_BIRD[0].getWidth(null);
    private int y = MyGame.gameH/2;
    private int count=0;

    public void draw(Graphics g) {
        g.drawImage(IMG_BIRD[currentFrame],x,y, null);
    }

    public void logic() {
         y+=speed;
         count++;
         if(count%4==0) {
         currentFrame++;
         }
         if(currentFrame>2) {
             currentFrame=0;
         }
    }

    public void flyUp(int upCount) {
        if(upCount<=4) {
            y-=20;
        }
        if(upCount>4 && upCount<=8) {
            y-=18;
        }
        if(upCount>8 && upCount<=12) {
            y-=16;
        }
        if(upCount>12 && upCount<16) {
            y-=14;
        }
        if(y<=0) {
            y=0;
        }
    }

    public boolean isCollision(int x1,int y1,int x2,int y2) {
        int w = this.IMG_BIRD[0].getWidth(null);
        int h = this.IMG_BIRD[0].getHeight(null);
        if(this.y<y1 && this.y+h<y1) {
            return false;
        }
        if(this.y>y2) {
            return false;
        }
        if(this.x+w<x1) {
            return false;
        }
        if(this.x>x2) {
            return false;
        }
        return true;
    }

    public boolean isFall() {
        int h = this.IMG_BIRD[0].getHeight(null);
        if(this.y+h>=MyGame.gameH) {
            return true;
        }
        return false;
    }
}

IMG_BIRD是小鳥飛行動畫的每一幀,在前面寫開始界面時也有類似的Image數組。currentFrame表示現在應該播放動畫的第幾幀。

draw方法沒什麼好說的,根據小鳥的x,y座標繪製小鳥。

logic方法,這裏和前面開始界面一樣,主循環每循環4次,播放動畫的下一幀。因爲我們的小鳥在不操作時是要不斷往下落的,所以每一幀,y+=speed,speed就是下落速度(swing的座標系是左上角爲原點,往下y爲正)。

flyUp方法,是當我們鼠標點擊屏幕時小鳥要向上飛,調用的方法,這裏爲了更真實,做了個處理(很笨的處理)。。根據上升的幀數,每次y減少的距離不同,這樣就有個越往上飛的越慢的效果。

isFall方法判斷小鳥是不是向下落出了屏幕。

這裏要着重講一講isCollision方法。

Collision方法用來判斷小鳥和正方形是否發生碰撞,isCollision(int x1,int y1,int x2,int y2),(x1,y1),(x2,y2)分別是小鳥的左上角和右下角座標。
如果單純考慮兩個正方形碰撞,那麼有很多情況,容易遺漏,這邊用排除法,找到不會碰撞的情況,剩下的
就是碰撞的情況了。
4種不會碰撞的情況
如圖所示,這4種情況下是不會碰撞的,轉化爲代碼就是下面這樣:

        int w = this.IMG_BIRD[0].getWidth(null);
        int h = this.IMG_BIRD[0].getHeight(null);
        if(this.y<y1 && this.y+h<y1) {
            return false;
        }
        if(this.y>y2) {
            return false;
        }
        if(this.x+w<x1) {
            return false;
        }
        if(this.x>x2) {
            return false;
        }
        return true;

其中w,h是小鳥的寬和高。除了4中不碰撞的情況,餘下的就是會發生碰撞的情況了。

好了,小鳥的Entity就介紹到這裏,下一篇我們講講怎麼做水管。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章