// 引入Unity和UI库 using UnityEngine; using UnityEngine.UI;

// 定义Bird类,继承自MonoBehaviour类 public class Bird : MonoBehaviour { // 定义公共变量 public float jumpForce = 10f; // 跳跃力度 public float speed = 5f; // 移动速度 public Text scoreText; // 分数文本 public Text highScoreText; // 最高分文本 public GameObject gameOverPanel; // 游戏结束面板

// 定义私有变量
private Rigidbody2D rb; // 刚体组件
private int score = 0; // 当前分数
private int highScore = 0; // 最高分数

// 定义枚举类型
private enum State { Playing, GameOver }; // 游戏状态
private State state; // 当前状态

// Start方法,初始化游戏
void Start()
{
    rb = GetComponent<Rigidbody2D>(); // 获取刚体组件
    highScore = PlayerPrefs.GetInt("HighScore", 0); // 获取最高分数
    highScoreText.text = "High Score: " + highScore.ToString(); // 显示最高分数
    scoreText.text = "Score: 0"; // 显示当前分数
    state = State.Playing; // 初始化游戏状态
}

// Update方法,每帧更新游戏
void Update()
{
    switch (state)
    {
        case State.Playing: // 游戏进行中
            if (Input.GetMouseButtonDown(0)) // 检测鼠标左键是否按下
            {
                rb.velocity = Vector2.up * jumpForce; // 给刚体施加向上的力
            }
            break;
        case State.GameOver: // 游戏结束
            if (Input.GetMouseButtonDown(0)) // 检测鼠标左键是否按下
            {
                RestartGame(); // 重新开始游戏
            }
            break;
    }
}

// FixedUpdate方法,每固定时间更新游戏
void FixedUpdate()
{
    switch (state)
    {
        case State.Playing: // 游戏进行中
            rb.velocity = Vector2.right * speed; // 给刚体施加向右的力
            break;
        case State.GameOver: // 游戏结束
            rb.velocity = Vector2.zero; // 刚体速度归零
            break;
    }
}

// OnTriggerEnter2D方法,检测触发器碰撞
void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Obstacle")) // 如果碰撞到障碍物
    {
        GameOver(); // 游戏结束
    }
    else if (other.CompareTag("Score")) // 如果碰撞到得分区域
    {
        score++; // 分数加1
        scoreText.text = "Score: " + score.ToString(); // 更新分数文本
        if (score > highScore) // 如果当前分数大于最高分数
        {
            highScore = score; // 更新最高分数
            highScoreText.text = "High Score: " + highScore.ToString(); // 更新最高分数文本
            PlayerPrefs.SetInt("HighScore", highScore); // 保存最高分数
        }
    }
}

// GameOver方法,游戏结束
void GameOver()
{
    gameOverPanel.SetActive(true); // 显示游戏结束面板
    state = State.GameOver; // 更新游戏状态
}

// RestartGame方法,重新开始游戏
public void RestartGame()
{
    state = State.Playing; // 更新游戏状态
    score = 0; // 分数归零
    scoreText.text = "Score: 0"; // 更新分数文本
    gameOverPanel.SetActive(false); // 隐藏游戏结束面板
    rb.position = Vector2.zero; // 刚体位置重置
}

// QuitGame方法,退出游戏
public void QuitGame()
{
    Application.Quit(); // 退出游戏
}

}

我叫szhs请帮我把这个代码加上注释using UnityEngine;using UnityEngineUI;public class Bird MonoBehaviour public float jumpForce = 10f; public float speed = 5f; public Text scoreText; public Text highScore

原文地址: https://www.cveoy.top/t/topic/bIT6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录