飞翔的小鸟

发布时间:2023年12月25日

一.准备工作
首先创建一个新的Java项目命名为“飞翔的鸟”,并在src中创建一个包命名为“com.qiku.bird",在这个包内分别创建4个类命名为“Bird”、

BirdGame”、“Column”、“Ground”,并向需要的图片素材导入到包内。

package com.qiku.bird;
?
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
?
/*
?* 小鸟类
?* */
public class Bird {
? ? int x;// 坐标
? ? int y;
? ? int width; // 宽高
? ? int height;
? ? BufferedImage image; // 图片
? ? BufferedImage[] images; // 小鸟所有图片
?
? ? public Bird() {
? ? ? ? // 初始化数组 保存八张图片
? ? ? ? images = new BufferedImage[8];
? ? ? ? // 使用循环结构 将小鸟所有图片 存入数组
? ? ? ? for (int i = 0; i < images.length; i++) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? images[i] = ImageIO.read(Bird.class.getResourceAsStream(i + ".png"));
? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? image = BirdGame.bird_image;
? ? ? ? width = image.getWidth();
? ? ? ? height = image.getHeight();
? ? ? ? x = 120;
? ? ? ? y = 240;
? ? }
?
? ? // 小鸟飞翔的方法
? ? int index = 0;
?
? ? public void fly() {
? ? ? ? image = images[index % images.length];
? ? ? ? index++;
? ? }
?
? ? // h = v * t + g * t * t / 2
? ? int g = 6; //重力加速度
? ? double t = 0.15; // 下落时间
? ? double v = 0; // 初速度
? ? double h = 0; // 下落距离
?
? ? //小鸟下落一次
? ? public void down() {
? ? ? ? h = v * t + g * t * t / 2; // 具体下落的距离
? ? ? ? v = v + g * t; // 末速度 = 当前速度 + 重力加速度 * 时间
? ? ? ? y += (int) h;
? ? }
?
? ? // 小鸟向上飞
? ? public void up() {
? ? ? ? // 给一个 负方向的初速度
? ? ? ? v = -30;
? ? }
? ? /*
? ? ?* 小鸟撞地面
? ? ?* */
? ? public boolean hitGround(Ground ground) {
? ? ? ? boolean isHit = this.y + this.height >= ground.y;
? ? ? ? return isHit;
? ? }
?
? ? // 小鸟撞天花板
? ? public boolean hitCeiling() {
? ? ? ? boolean isHit = this.y <= 0;
? ? ? ? return isHit;
? ? }
?
? ? // 小鸟撞柱子
? ? public boolean hitColumn(Column c) {
? ? ? ? boolean b1 = this.x + this.width >= c.x;
? ? ? ? boolean b2 = this.x <= c.x + c.width;
? ? ? ? boolean b3 = this.y <= c.y + c.height / 2 - c.gap / 2;
? ? ? ? boolean b4 = this.y + this.height >= c.y + c.height / 2 + c.gap / 2;
? ? ? ? // 满足b1 b2表示水平方向 相撞 b1 b2 b3 同时满足 撞上柱子 b1 b2 b4 同时满足撞下柱子
? ? ? ? return b1 && b2 && (b3 || b4);
?
? ? }
?
}

结果呈现

文章来源:https://blog.csdn.net/2302_76552040/article/details/135188829
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。