使用unity依赖,C#编写直播互动游戏躲猫猫代码
时间: 2023-12-10 14:41:11 浏览: 243
以下是一个简单的躲猫猫游戏的代码示例,使用Unity和C#编写。这个游戏中,一个玩家是猫,其他玩家是老鼠。猫需要追逐老鼠,老鼠需要躲避猫,如果猫抓住了老鼠,老鼠就会变成猫。
```csharp
using UnityEngine;
using System.Collections.Generic;
public class HideAndSeekGame : MonoBehaviour {
public GameObject catPrefab;
public GameObject mousePrefab;
public Transform[] spawnPoints;
public float gameDuration = 60f;
public int miceToWin = 3;
private List<GameObject> mice = new List<GameObject>();
private GameObject cat;
private float gameTimer;
private int miceCaught;
void Start () {
// Spawn the cat
int catSpawnPoint = Random.Range(0, spawnPoints.Length);
cat = Instantiate(catPrefab, spawnPoints[catSpawnPoint].position, Quaternion.identity) as GameObject;
// Spawn the mice
for (int i = 0; i < spawnPoints.Length; i++) {
if (i != catSpawnPoint) {
GameObject mouse = Instantiate(mousePrefab, spawnPoints[i].position, Quaternion.identity) as GameObject;
mice.Add(mouse);
}
}
// Set game timer
gameTimer = gameDuration;
}
void Update () {
if (gameTimer > 0f) {
// Count down the game timer
gameTimer -= Time.deltaTime;
// Check if a mouse has been caught
foreach (GameObject mouse in mice) {
MouseController controller = mouse.GetComponent<MouseController>();
if (controller.caught) {
miceCaught++;
mice.Remove(mouse);
Destroy(mouse);
}
}
// Check if the game is over
if (miceCaught >= miceToWin) {
Debug.Log("Mice win!");
EndGame();
} else if (gameTimer <= 0f) {
Debug.Log("Cat wins!");
EndGame();
}
}
}
void EndGame () {
// Destroy all remaining mice
foreach (GameObject mouse in mice) {
Destroy(mouse);
}
mice.Clear();
// Destroy the cat
Destroy(cat);
// Restart the game
Start();
}
}
```
这个代码中,我们首先在 Start() 函数中生成一个猫和多个老鼠。然后,在 Update() 函数中,我们不断检查老鼠是否被猫抓住,如果有老鼠被抓住了,我们就将其从老鼠列表中删除,并将抓住的老鼠数量加1。如果猫抓住了足够数量的老鼠,老鼠赢得了游戏,否则猫赢得了游戏。
当游戏结束时,我们调用 EndGame() 函数来清理游戏场景,并重新开始游戏。
阅读全文