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就介绍到这里,下一篇我们讲讲怎么做水管。

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