-
创建Unity项目:
-
使用Unity Hub新建3D项目
-
设置目标平台为Windows
-
场景搭建:
csharp
// 地鼠控制器 WhackAMole.cs
using UnityEngine;
using System.Collections;
public class WhackAMole : MonoBehaviour {
public float popupDuration = 1.5f;
public float minHideTime = 1.0f;
public float maxHideTime = 3.0f;
private bool isPoppedUp = false;
void Start() {
StartCoroutine(MoleBehavior());
}
IEnumerator MoleBehavior() {
while(true) {
yield return new WaitForSeconds(Random.Range(minHideTime, maxHideTime));
PopUp();
yield return new WaitForSeconds(popupDuration);
Hide();
}
}
void PopUp() {
transform.localPosition = new Vector3(0, 1, 0);
isPoppedUp = true;
}
void Hide() {
transform.localPosition = new Vector3(0, 0, 0);
isPoppedUp = false;
}
void OnMouseDown() {
if(isPoppedUp) {
GameManager.Instance.AddScore(10);
Hide();
}
}
}
-
游戏管理器:
csharp
// GameManager.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameManager : MonoBehaviour {
public static GameManager Instance;
public Text scoreText;
public Text timerText;
public GameObject gameOverPanel;
private int score = 0;
private float gameTime = 60f;
private bool isGameActive = true;
void Awake() {
Instance = this;
}
void Update() {
if(isGameActive) {
gameTime -= Time.deltaTime;
timerText.text = "Time: " + Mathf.RoundToInt(gameTime);
if(gameTime <= 0) {
EndGame();
}
}
}
public void AddScore(int points) {
score += points;
scoreText.text = "Score: " + score;
}
void EndGame() {
isGameActive = false;
gameOverPanel.SetActive(true);
Time.timeScale = 0;
}
public void RestartGame() {
Time.timeScale = 1;
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
-
场景设置步骤:
-
创建平面作为地面
-
创建多个圆柱体作为"地洞",调整Y轴位置使其半埋入地面
-
为每个地洞创建子物体胶囊体作为"地鼠"
-
给每个地鼠添加WhackAMole脚本
-
创建UI Canvas包含:
-
Score Text (右上角)
-
Timer Text (左上角)
-
Game Over Panel (居中,包含最终分
-