Unity mini game - flying saucer
I developed a simple and interesting flying saucer game using the Unity engine and C# programming language. In the game, players need to click on the flying saucer. As the number of flying saucers hit increases, the player's score will also increase. I will introduce the main functions of the game step by step and the key points in the implementation process.
Game overview
This is a simple and interesting flying saucer game. Players need to click on the flying saucer. Each time they click on the flying saucer, the score increases. When the score reaches a certain value, the game ends and the victory message is displayed. The flying saucer in the game will appear randomly on the screen, and players need to click on the flying saucer as soon as possible after it appears to get higher scores.
Game elements
1. UFO object
- Flying saucers come in different colors.
- The flying saucer has random directions and speeds, and forces and moments are randomly applied to the flying saucer, making the game more difficult and interesting.
2. Points system
- Each time the player clicks on the flying saucer, the score increases.
- The score is displayed on the game interface and is dynamically updated as the score increases.
3. Game process control
- When the game starts, flying saucers start appearing randomly.
- After the player clicks on the flying saucer, the flying saucer disappears and the score increases.
- When the player's score reaches a certain value, the game ends and victory information is displayed.
game design
1. UFO generation
- Use object pool technology to generate a certain number of flying saucer objects in advance to avoid frequent creation and destruction of objects while the game is running.
- The direction and speed of the flying saucer are randomly generated and can appear at different locations on the screen.
2. UFO interaction
- When the player clicks on the flying saucer, the flying saucer disappears and the score increases.
3. Score calculation
- Each time the flying saucer is clicked, the player's score increases. The specific increase score is a random number between the maximum and minimum scores set in the ScriptableObject.
4. Game over
- When the player's score reaches a certain value, the game ends.
- After the game is over, a victory message is displayed to inform the player that they have won.
Design implementation
Flying saucer prefab production
Which requires Rigidbody, Box Collider and Mesh Rednderer
The principle of object pool
In the following UML diagram, the basic principles and key components of object pooling are shown, including DiskPool
class, DiskConfig
class and DiskController
class.
Pseudocode - principle of object pooling
The following is pseudocode describing the basic principles of object pooling:
class DiskPool:
- diskPrefab: GameObject
- diskPool: Queue<GameObject>
constructor(diskPrefab: GameObject):
this.diskPrefab = diskPrefab
this.diskPool = new Queue<GameObject>()
InitializePool()
method InitializePool():
for i from 0 to 10:
disk = Instantiate(diskPrefab)
disk.SetActive(false)
diskPool.Enqueue(disk)
method GetDiskFromPool(): GameObject:
if diskPool is not empty:
disk = diskPool.Dequeue()
disk.SetActive(true)
return disk
else:
newDisk = Instantiate(diskPrefab)
return newDisk
method ReturnDiskToPool(disk: GameObject):
disk.SetActive(false)
diskPool.Enqueue(disk)
method RecycleDisk(disk: GameObject):
yield return WaitForSeconds(5)
ReturnDiskToPool(disk)
Object configuration method
Configuring different flying saucers using ScriptableObject
Pseudocode - object configuration methods
The following is pseudocode describing the object configuration methods:
class DiskConfig (ScriptableObject):
- MinSpeed: float
- MaxSpeed: float
- MinScore: int
- MaxScore: int
class DiskPool:
- diskConfigs: DiskConfig
- diskPrefab: GameObject
- diskPool: Queue<GameObject>
method InitializePool():
for i in range(10):
disk = Instantiate(diskPrefab)
// 根据diskConfigs中的配置调整disk的属性
disk.SetActive(false)
diskPool.Enqueue(disk)
method GetDiskFromPool(): GameObject:
if diskPool is not empty:
return diskPool.Dequeue()
else:
newDisk = Instantiate(diskPrefab)
// 根据diskConfigs中的配置调整newDisk的属性
return newDisk
method ReturnDiskToPool(disk: GameObject):
disk.SetActive(false)
diskPool.Enqueue(disk)
class DiskController:
- diskConfig: DiskConfig
- minForce: float
- maxForce: float
- randomTorque: float
- speed: float
- diskscore: int
method Awake():
// 初始化速度和分数
// 根据diskConfig中的配置调整属性
method OnEnable():
// 添加力和扭矩,启用时调用
method OnMouseDown():
// 处理鼠标点击事件,增加分数并回收飞碟
method SetColor():
// 设置飞碟颜色
method SetMovementParameters(direction: Vector3):
// 设置飞碟的移动参数
class ScoreManager:
- score: int
- diskConfig: DiskConfig
method IncreaseScore(diskscore: int):
score += diskscore
if score >= diskConfig.MaxScore:
// 游戏胜利逻辑
overall design
The overall design pseudocode of the game includes the logic of game management, object pool, object configuration and score management.
class GameManager:
- Instance: GameManager
- gameStarted: bool
method Awake():
Instance = this
method StartGame():
gameStarted = true
method EndGame(message: string):
gameStarted = false
// 显示游戏结束消息
class DiskPool:
- Instance: DiskPool
- diskConfigs: DiskConfig
- diskPool: Queue<GameObject>
method Awake():
Instance = this
method GetDiskFromPool(): GameObject:
if diskPool is not empty:
return diskPool.Dequeue()
else:
newDisk = Instantiate(diskConfigs.diskPrefab)
return newDisk
method ReturnDiskToPool(disk: GameObject):
disk.SetActive(false)
diskPool.Enqueue(disk)
class DiskController:
- minForce: float
- maxForce: float
- randomTorque: float
- speed: float
- diskscore: int
method OnEnable():
// 添加力和扭矩,启用时调用
method OnMouseDown():
// 处理鼠标点击事件,增加分数并回收飞碟
method SetColor():
// 设置飞碟颜色
method SetMovementParameters(direction: Vector3):
// 设置飞碟的移动参数
class ScoreManager:
- Instance: ScoreManager
- score: int
method Awake():
Instance = this
method IncreaseScore(diskscore: int):
score += diskscore
if score >= 50:
GameManager.Instance.EndGame("You Win!")
Implementation
During the development process of the game, we made full use of the physics engine of the Unity engine, used the C# programming language to write game logic, and realized the generation, interaction and score management of flying saucers. The following are some key points in our specific implementation:
UFO configuration and object pool management
We used theDiskConfig
class to configure the appearance and movement parameters of the flying saucer, including color, initial speed and random direction range. In this way, we can achieve the appearance and movement characteristics of different flying saucers by adjustingDiskConfig
's properties.
// DiskConfig类(DiskConfig.cs文件中)
public class DiskConfig : ScriptableObject
{
public float MinSpeed;
public float MaxSpeed;
public int MinScore;
public int MaxScore;
}
// DiskPool类(DiskPool.cs文件中)
public class DiskPool : MonoBehaviour
{
// ...
}
In theDiskPool
class, we use object pool technology to manage flying saucer objects, which improves game performance and efficiency. At the beginning of the game, we initialize a certain number of flying saucer objects and obtain the flying saucers from the object pool when needed, avoiding the frequent creation and destruction of objects.
// DiskPool类中的初始化飞碟对象池方法
private void InitializePool()
{
foreach (var config in diskConfigs)
{
for (int i = 0; i < 10; i++) // 初始化10个飞碟对象
{
GameObject disk = Instantiate(diskPrefab, transform);
disk.GetComponent<Renderer>().material.color = config.diskColor;
disk.SetActive(false);
diskPool.Enqueue(disk);
}
}
}
UFO control and interaction
The control and interaction of the flying saucer are mainly implemented in theDiskController
class. In the Awake()
method, we initialize the speed and score of the flying saucer according to the configuration in DiskConfig
. In the OnEnable()
method, we apply random force and rotation force to the flying saucer, so that the flying saucer has a random trajectory in the game. When the player clicks on the flying saucer, the OnMouseDown()
method is triggered, the score is increased, and the flying saucer is recycled to the object pool.
// DiskController类中的控制和交互方法
private void Awake()
{
// 根据DiskConfig中的配置初始化飞碟的速度和分数
speed = Random.Range(diskConfig.initialSpeed - diskConfig.randomDirectionRange, diskConfig.initialSpeed + diskConfig.randomDirectionRange);
diskscore = Random.Range(diskConfig.MinScore, diskConfig.MaxScore);
}
private void OnEnable()
{
// 给飞碟施加随机的力和旋转力
rb.AddForce(Random.Range(minForce, maxForce) * transform.forward);
rb.AddTorque(Random.onUnitSphere * randomTorque);
}
private void OnMouseDown()
{
// 处理鼠标点击事件,增加分数并回收飞碟
ScoreManager.Instance.IncreaseScore(diskscore);
DiskPool.Instance.ReturnDiskToPool(gameObject);
}
Score management and game flow control
The management of scores is implemented in theScoreManager
class. Each time you click on the flying saucer, the score increases. When the score reaches a certain value, the game ends.
// ScoreManager类中的分数管理方法
public void IncreaseScore(int diskscore)
{
// 增加分数并检查是否满足胜利条件
score += diskscore;
UpdateScoreText();
if (score >= 50)
{
// 游戏胜利逻辑,例如显示胜利信息
score = 0;
UpdateScoreText();
GameManager.Instance.EndGame("You Win!");
}
}
The control of game flow is implemented in theGameManager
class. At the beginning of the game, flying saucers will be generated at certain intervals. When the player clicks on the flying saucer, the score increases. When the player's score reaches the victory condition, the game ends and victory information is displayed.
The game prompt information and buttons are implemented through the Canvas UI.
// GameManager类中的游戏流程控制方法
private void Start()
{
// 游戏开始,开始生成飞碟
InvokeRepeating("SpawnDisk", 1f, spawnInterval);
}
private void SpawnDisk()
{
if (gameStarted)
{
// 生成飞碟的逻辑,使用DiskPool来获取飞碟对象
// ...
}
}
public void EndGame(string message)
{
// 游戏结束,显示胜利信息或失败信息
gameStarted = false;
restartButton.gameObject.SetActive(true);
Debug.Log(message);
winText.enabled = true;
winText.gameObject.SetActive(true);
}
public void RestartGame()
{
// 重新开始游戏,重置分数等游戏状态
winText.enabled = false;
winText.gameObject.SetActive(false);
StartGame();
}
During the development process of the game, we gave full play to the advantages of the Unity engine and C# programming language, and managed flying saucer objects through object pool technology, which improved the performance and efficiency of the game. At the same time, by configuring differentDiskConfig
objects, we have diversified the flying saucers, adding fun and challenge to the game.
Summarize
Through this development practice, I learned how to use object pool technology to manage game objects, which improved the performance and efficiency of the game. At the same time, I also deeply understood the interaction logic of each part of the game, including the generation, interaction and score management of flying saucers.
Video display
Unity game-flying saucer