In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how Unity implements the game of bomber. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Preface
Take a look at the effect of the bomber Mini Game!
Production idea
The old rule, before we do it, let's straighten out the idea of making this Mini Game. Let's think about what's in a bomber's Mini Game.
First of all, there should be a game scene, which is what we can see when the game is running.
There will be many walls in this scene, among which there will be a game edge wall, these walls can not be destroyed by our bomb, call it super wall!
There will also be some walls in the scene, which can be destroyed, and we will become ordinary walls.
Some are fixed, some can be destroyed, this is a classic bomber play!
Secondly, we should have a protagonist, that is, our bomber!
Our protagonist can move up and down, left and right, and then he can "lay eggs", that is, to plant bombs and blow up the enemy.
And then there will be blood volume and so on.
Of course, there are enemies. We add an enemy to the scene that can move randomly from side to side, and it will make us bleed when we meet us.
This is also the most classic and basic way to play.
At first glance, it seems that there are only so few things, but it is not very difficult.
Then let's get started now!
Start production
Import material resource pack
After import, the engineering resources look like this
There are some genie picture materials that are used as protagonists, enemies and walls for us.
There are also a few simple sound and animation effects to provide logistical support for our game production!
The first step: game scene making
We are a 2D game, and in the game scene here, the map is made of elf pictures.
Let's write a script here and let him generate the corresponding map directly when the game is running.
Here is an object pool script ObjectPool, which is used to get all the resources in the project, and then generated from the object pool to the scene when needed.
I won't talk about object pooling here. There are many ways.
A reference is provided here, which can be directly linked to the scene and used.
The above code:
Public enum ObjectType {SuperWall, Wall, Prop, Bomb, Enemy, BombEffect} [System.Serializable] public class Type_Prefab {public ObjectType type; public GameObject prefab;} public class ObjectPool: MonoBehaviour {public static ObjectPool Instance; public List type_Prefabs = new List () / / get the preform / private GameObject GetPreByType (ObjectType type) {foreach (var item in type_Prefabs) {if (item.type = = type) return item.prefab;} return null through the object type } / object type and corresponding object pool relation dictionary / private Dictionary dic = new Dictionary (); private void Awake () {Instance = this } / public GameObject Get (ObjectType type, Vector2 pos) {GameObject temp = null from the corresponding object pool by object type / / determine whether there is an object pool matching this type in the dictionary. If not, create if (dic.ContainsKey (type) = = false) dic.Add (type, new List ()); / / determine whether there is an object if (dictype] .count > 0) {int index = dicty.count-1 Temp = dic [type] [index]; Dictype.RemoveAt (index);} else {GameObject pre = GetPreByType (type); if (pre! = null) {temp = Instantiate (pre, transform);}} temp.SetActive (true) Temp.transform.position = pos; temp.transform.rotation = Quaternion.identity; return temp } / Recycling / public void Add (ObjectType type GameObject go) {/ / determine whether there is a corresponding object pool for this type and that the object does not exist in the object pool if (dic.ContainsKey (type) & & dict [type] .Concluded (go) = = false) {/ / put into the object pool dic[ type] .add (go) } go.SetActive (false);}}
With this simple object pool, we write a script MapController to generate some walls in the scene
Generate ordinary walls and super walls through a list of two two-dimensional vectors
We need to mark the preforms with different Tag to distinguish their respective attributes.
Add all the following preforms, only the wall needs to add layer layer, which will be used later when the monster moves randomly, and the rest just need to add Tag.
The above code:
Public class MapController: MonoBehaviour {public GameObject doorPre; public int X, Y; private List nullPointsList = new List (); private List superWallPointList = new List (); private GameObject door; / / represents the collection of all objects taken from the object pool private Dictionary poolObjectDic = new Dictionary () / determine whether the current location is a solid wall / public bool IsSuperWall (Vector2 pos) {if (superWallPointList.Contains (pos)) return true; return false;} public Vector2 GetPlayerPos () {return new Vector2 (- (X + 1), (Y-1) } private void Recovery () {nullPointsList.Clear (); superWallPointList.Clear (); foreach (var item in poolObjectDic) {foreach (var obj in item.Value) {ObjectPool.Instance.Add (item.Key, obj);}} poolObjectDic.Clear () } public void InitMap (int x, int y, int wallCount, int enemyCount) {Recovery (); X = x; Y = y; CreateSuperWall (); FindNullPoints (); CreateWall (wallCount); CreateDoor (); CreateProps (); CreateEnemy (enemyCount) } / generate solid wall / private void CreateSuperWall () {for (int x =-X; x)
< X; x+=2) { for (int y = -Y; y < Y; y+=2) { SpawnSuperWall(new Vector2(x, y)); } } for (int x = -(X + 2); x 0) { AudioController.Instance.PlayFire(); bombCount--; GameObject bomb = ObjectPool.Instance.Get(ObjectType.Bomb, new Vector3(Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.y))); bomb.GetComponent().Init(range, bombBoomTime, () =>{bombCount++; bombList.Remove (bomb);}); bombList.Add (bomb);}}
Then there is an animation controller on the bomber, which is used to play different animations when the bomber moves up and down, left and right.
There are all animation clips in the resource kit. Let's just set them up. Very simple animation clips can be executed.
The effect of switching animation clips:
A simple move effect in a scene:
There is also the method code for playing animation when the character dies.
/ end animation / public void PlayDieAnim () {Time.timeScale = 0; anim.SetTrigger ("Die");} / end animation playback finished / private void DieAnimFinish () {GameController.Instance.GameOver ();}
Death animation effect:
Step 4: bomb disposal
Now that we have the bomber and the preform of the bomb, that is the elf picture.
And now we need to mount the script in order for the bomb to explode in all directions!
There is a script Bomb on the bomb, and the initialization method Init is called when the bomber drops the bomb in PlayerCtrl! The DealyBoom method in the script is used to deal with the explosive range that can be inspected after being thrown by our bomber.
Then there is also a preform after the bomb explodes, and we also need to mount a script on it to perform an explosion effect after the bomb explodes!
Script Bomb and BombEffect:
Public class Bomb: MonoBehaviour {private int range; private Action aniFinAction; public void Init (int range, float dealyTime, Action action) {this.range = range; StartCoroutine ("DealyBoom", dealyTime); aniFinAction = action;} IEnumerator DealyBoom (float time) {yield return new WaitForSeconds (time); if (aniFinAction! = null) aniFinAction (); AudioController.Instance.PlayBoom () ObjectPool.Instance.Get (ObjectType.BombEffect, transform.position); Boom (Vector2.left); Boom (Vector2.right); Boom (Vector2.down); Boom (Vector2.up); ObjectPool.Instance.Add (ObjectType.Bomb, gameObject);} private void Boom (Vector2 dir) {for (int I = 1) I = 1 & & info.IsName ("BombEffect") {ObjectPool.Instance.Add (ObjectType.BombEffect, gameObject);}} step 5: enemy production
Now that we have the scene and the protagonist, we naturally need to create enemies.
We also put the enemy generation in the script that controls the wall generation, because the enemy can also be regarded as a movable wall.
It's just that we give him different material, which makes him more special than the wall.
So we added a new method to MapController to generate enemies.
Generate enemy code
Private void CreateEnemy (int count) {for (int I = 0; I)
< count; i++) { int index = Random.Range(0, nullPointsList.Count); GameObject enemy = ObjectPool.Instance.Get(ObjectType.Enemy, nullPointsList[index]); enemy.GetComponent().Init(); nullPointsList.RemoveAt(index); if (poolObjectDic.ContainsKey(ObjectType.Enemy) == false) poolObjectDic.Add(ObjectType.Enemy, new List()); poolObjectDic[ObjectType.Enemy].Add(enemy); } } 然后敌人生成以后还要可以自由移动,然后寻找我们的炸弹人,只要碰到我们的炸弹人,炸弹人就会受到伤害 这里需要注意的细节还是挺多的,首先我们需要让他上下左右随机移动 移动是通过射线检测来判断的,这里我们给场景中的墙体的layer设置成8层 然后怪物在检测的时候,只检测第八层的物体来判断自身是否可以向该方向移动 还要处理敌人在碰到炸弹人和他们的同类时,会改变自身的颜色,这样会有一个简单的视觉交互效果 上脚本EnemyAI脚本代码 public class EnemyAI : MonoBehaviour{ private float speed = 0.04f; private Rigidbody2D rig; private SpriteRenderer spriteRenderer; private Color color; /// /// 方向:0上 1下 2左 3右 /// private int dirId = 0; private Vector2 dirVector; private float rayDistance = 0.7f; private bool canMove = true; //是否可以移动 private void Awake() { spriteRenderer = GetComponent(); color = spriteRenderer.color; rig = GetComponent(); } /// /// 初始化方法 /// public void Init() { color.a = 1; //当敌人穿过后离开时,恢复之前颜色 spriteRenderer.color = color; canMove = true; InitDir(Random.Range(0, 4)); } /// /// 初始化敌人方向 /// /// private void InitDir(int dir) { dirId = dir; switch (dirId) { case 0: dirVector = Vector2.up; break; case 1: dirVector = Vector2.down; break; case 2: dirVector = Vector2.left; break; case 3: dirVector = Vector2.right; break; default: break; } } private void Update() { if (canMove) rig.MovePosition((Vector2)transform.position + dirVector * speed); else ChangeDir(); } private void OnTriggerEnter2D(Collider2D collision) { //消灭敌人 if(collision.CompareTag(Tags.BombEffect) && gameObject.activeSelf) { GameController.Instance.enemyCount--; ObjectPool.Instance.Add(ObjectType.Enemy, gameObject); } if (collision.CompareTag(Tags.Enemy)) { color.a = 0.3f; //当敌人相互穿过时,改变其颜色为半透明 spriteRenderer.color = color; } if (collision.CompareTag(Tags.SuperWall) || collision.CompareTag(Tags.Wall)) { //复位 transform.position = new Vector2(Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.y)); //RoundToInt取整 ChangeDir(); } } private void OnTriggerStay2D(Collider2D collision) { if (collision.CompareTag(Tags.Enemy)) { color.a = 0.3f; //当敌人在一块时,改变其颜色为半透明 spriteRenderer.color = color; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag(Tags.Enemy)) { color.a = 1; //当敌人穿过后离开时,恢复之前颜色 spriteRenderer.color = color; } } private void ChangeDir() { List dirList = new List(); if (Physics2D.Raycast(transform.position, Vector2.up, rayDistance, 1 { Time.timeScale = 1; //重新加载当前正在运行的场景 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); }); gameOverPanel.transform.Find("btn_Main").GetComponent().onClick.AddListener(() =>{Time.timeScale = 1; SceneManager.LoadScene ("Start");} public void Refresh (int hp, int level, int time, int enemy) {txt_HP.text = "HP:" + hp.ToString (); txt_Level.text = "Level:" + level.ToString (); txt_Time.text = "Time:" + time.ToString () Txt_Enemy.text = "Enemy:" + enemy.ToString ();} public void ShowGameOverPanel () {gameOverPanel.SetActive (true);} / play the level prompt animation / public void PlayLevelFade (int levelIndex) {Time.timeScale = 0 LevelFadeAnim.transform.Find ("txt_Level"). GetComponent (). Text = "Level" + levelIndex.ToString (); levelFadeAnim.Play ("LevelFade", 0,0); startDelay = true;} private bool startDelay = false; private float timer = 0; private void Update () {if (startDelay) {timer + = Time.unscaledDeltaTime If (timer > 0.7f) {startDelay = false; Time.timeScale = 1; timer = 0;} Thank you for reading! This is the end of this article on "how to realize the bomber game in Unity". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.