Hello everyone, I'm Qin Yuanpei. Welcome to continue to follow my blog. My blog address is blog.csdn.net/qinyuanpei.
First of all, I would like to thank you for your attention to my blog. Today I want to share with you a project of the aircraft war. This is a comprehensive project. I hope it will help you learn Unity3D. I will give the project code at the end of the article. As a game, game planning is very important, so before starting today's article, let's first take a look at the planning of this project. Our players are A plane. Players can use four key positions A, D, S, and W to control the plane's position. When the Space key is pressed, our plane can launch shells to the enemy plane, when an attack occurs on an enemy plane, the life of the attack will be reduced. when the life of the enemy plane is 0, the enemy plane will be destroyed. In the game scenario, there is only one type of enemy plane that keeps flying down from the top of the screen. When our plane and the enemy plane collide, both sides will lose their lives. When our lifetime is reduced to 0, the game will end. Now, after learning about the game rule settings, we can start today's content.
I. game scenarios
The game scenario uses a 2D interface. We create a plane scenario with blue sky and white clouds, which is perpendicular to the camera and adopts orthogonal projection. If you are still confused about creating a 2D scene in Unity3D, refer to the article [Unity3D] Unity3D game development-Implementation of the classic brick game and Unity3D game development. develop 2D games (1) two articles.
Here we add a GUIText object in the scenario to display basic information such as the player score. The script is defined as follows:
Using UnityEngine; using System. collections; public class GameManager: MonoBehaviour {// private Transform Grade for players; // private Transform HP for Player life; // private Transform Text for game end; // private GameObject Player for players; void Start () {// initialization interface Grade = transform. find ("Grade"); HP = transform. find ("HP"); Text = transform. find ("Text"); Text. guiText. enabled = false; // obtain the Player Object Player = GameObject. find ("Player");} void Update () {if (P Layer! = Null) {// update UI Grade. guiText. text = "score:" + Player. getComponent <Player> (). grade. toString (); HP. guiText. text = "life:" + Player. getComponent <Player> (). maxHP. toString ();} if (HP. guiText. text = "Life: 0") {Text. guiText. enabled = true; // immediately restore if (Input. getKey (KeyCode. y) {Application. loadLevel ("Main");} // exit if (Input. getKey (KeyCode. n) {Application. quit ();}}}}
Ii. gamer planes
The creation of a gamer plane is the same as that of the background. A gamer plane must handle the movement, launch, and collision events. For this reason, we compile the following script:
Using UnityEngine; using System. collections; public class Player: MonoBehaviour {// The motion speed of an airplane public float MoveSpeed; // The maximum life of an airplane public int MaxHP = 100; // define the Bullet object public GameObject Bullet; // define the position where the bullet is fired. private Transform BulletPosL; private Transform BulletPosR; [HideInInspector] public int Grade = 0; void Start () {BulletPosL = this. transform. find ("BulletPosL"); BulletPosR = this. transform. find ("BulletPosR");} void Update () {if (Input. getKey (KeyCode. a) {transform. translate (Vector3.left * Time. deltaTime * (-MoveSpeed);} if (Input. getKey (KeyCode. d) {transform. translate (Vector3.left * Time. deltaTime * MoveSpeed);} if (Input. getKey (KeyCode. w) {transform. translate (Vector3.forward * Time. deltaTime * (-MoveSpeed);} if (Input. getKey (KeyCode. s) {transform. translate (Vector3.forward * Time. deltaTime * MoveSpeed);} // press the Space key to launch the bullet if (Input. getKey (KeyCode. space) {Instantiate (Bullet, BulletPosL. transform. position, Quaternion. euler (new Vector3 (0, 1); Instantiate (Bullet, BulletPosR. transform. position, Quaternion. identity) ;}# region blood loss public void Hit (int Value) {if (MaxHP> 0) {MaxHP-= Value;} else {Destroy (this. gameObject) ;}# endregion # region increase score public void Add (int Value) {Grade + = Value ;}# endregion}
In this Code, Bullet is our Bullet object. It is fired from the two Bullet positions of the plane, BulletPosL and BulletPosR, and moves slowly to the top of the screen at a certain speed, when a bullet hits the enemy, the bullet object is destroyed, and the enemy's life value is reduced. The Bullet object corresponds to one of our Prefab objects. BulletPosL and BulletPosR correspond to the two locations on the aircraft.
Our Bullet is a Capsule bound to the script. Its code is defined as follows:
Using UnityEngine; using System. collections; public class Bullet: MonoBehaviour {// defines the speed at which a Bullet moves. public float MoveSpeed = 10F; // defines the time when a Bullet is destroyed. public float DestroyTime = 2.0F; // define the Damage value of a bullet to the enemy public int Damage = 2; // private GameObject Player of the Player plane; void Start () {Player = GameObject. find ("Player");} void Update () {// move the bullet transform. translate (Vector3.up * MoveSpeed * Time. deltaTime);} // collision event capture void OnTriggerEnter (Collider mCollider) {if (mCollider. gameObject. tag = "Enemy") {// Enemy blood loss mCollider. gameObject. getComponent <Enemy> (). hit (Damage); // we score Player. getComponent <Player> (). add (1); // Destroy the bullet Destroy (this. gameObject) ;}}// the Destroy event void OnBecameInvisible () {Destroy (this. gameObject );}}
Iii. Enemy planes
There are three types of enemy planes in our game. Let's make them into presets first. Then, the enemy machine is continuously generated through the enemy machine generator.
In contrast to bullets, we want the enemy plane to move down at a certain speed from the top of the screen. When a player encounters a plane or bullet, it will reduce its life. To this end, we define the scripts of the enemy:
Using UnityEngine; using System. collections; public class Enemy: MonoBehaviour {// mobile speed public float MoveSpeed = 1.5F; // Explosion public GameObject Explosion; // maximum life value public int MaxHP = 100; void Update () {// Mobile Aircraft transform. translate (Vector3.forward * Time. deltaTime * MoveSpeed);} public void Hit (int Value) {// if the blood volume is not lower than 0, the enemy's plane loses blood if (MaxHP> 0) {MaxHP-= Value ;} else {// Instantiate (Explosion, transform. position, Quaternion. euler (new Vector3 (90,180, 0); // Destroy the Destroy (this. gameObject) ;}} void OnTriggerEnter (Collider mCollider) {// if a player encounters a plane, both parties lose blood if (mCollider. gameObject. tag = "Player") {// the enemy's machine loses blood. this. hit (2); // Transform mPlayer = mCollider. gameObject. transform. find ("Player"); mPlayer. getComponent <Player> (). hit (2) ;}} void OnBecameInvisible () {Destroy (this. gameObject );}}Next, we use the enemy machine generator to continuously generate the enemy machine. The enemy generator is an empty game body pre-fabricated in a game scenario. It is located at the top of the game scenario. We bind the following script to the game generator so that it can continuously generate enemies:
Using UnityEngine; using System. collections; public class SpawnEnemy: MonoBehaviour {// defines the Enemy speed public float SpawnTime = 1.0f; // defines the array of enemy objects public GameObject [] Enemys; void Start () {StartCoroutine ("Spawn");} // generate the enemy IEnumerator Spawn () {// wait for yield return new WaitForSeconds (SpawnTime ); // clone object Instantiate (Enemys [Random. range (0, 3)], new Vector3 (transform. position. x * Random. range (-1F, 1F), transform. position. y,-4), Quaternion. euler (new Vector3 (90,180, 0); StartCoroutine ("Spawn ");}}The Enemys correspond to our enemy preset. At intervals, we randomly generate an enemy that will move slowly down from the top of the screen.
Iv. Collision Detection
In this game, there are mainly two forms of collision between bullets and enemy planes, and between player planes and enemy planes. They are defined in Bullet. cs and Enemy. cs files respectively.
// Collision event capture void OnTriggerEnter (Collider mCollider) {if (mCollider. gameObject. tag = "Enemy") {// Enemy blood loss mCollider. gameObject. getComponent <Enemy> (). hit (Damage); // we score Player. getComponent <Player> (). add (1); // Destroy the bullet Destroy (this. gameObject );}}
Void OnTriggerEnter (Collider mCollider) {// if the player encounters a plane, both sides lose blood if (mCollider. gameObject. tag = "Player") {// the enemy's machine loses blood. this. hit (2); // Transform mPlayer = mCollider. gameObject. transform. find ("Player"); mPlayer. getComponent <Player> (). hit (2 );}}
V. explosive effects
When an enemy machine is destroyed, the explosion effect will be displayed. Here we use a set of 2D textures to implement the explosion effect. The principle is to change the attributes of mainTextureScale and mainTextureOffset of the texture. Let's take a look at the Code:
Using UnityEngine; using System. collections; public class Explosion: MonoBehaviour {// animation sequence index private int index = 0; // sound private AudioSource mAudio; void Start () {mAudio = GetComponent <AudioSource> () ;}void FixedUpdate () {if (index <8) {this. renderer. sharedMaterial. mainTextureScale = new Vector2 (1.0F/8, 1); this. renderer. sharedMaterial. mainTextureOffset = new Vector2 (index * 1.0F/8, 0); index + = 1;} else {mAudio. play (); Destroy (this. gameObject );}}}MAudio corresponds to an AudioSource component. Here we specify an explosive sound effect. Similarly, we create an Explosion as a preset, which corresponds to the Explosion in Enemy. cs.
Now, today's content is completely explained. Let's take a look at the final effect!
I hope you will like the content today. After learning Unity3D for such a long time, I still feel a lot of emotion. If you don't try to do many things, you will never do well. You don't have to put pressure on yourself, you don't know how good you are. The source code of this project can be downloaded from here.
Daily proverbs: no matter what age you live to, you will always have to think too much, worry and confusion. If a person loses this and is comfortable with the status quo, it is the end of the true sense of youth. -- YuanYi
If you like my blog, please remember my name: Qin Yuanpei. My blog address is blog.csdn.net/qinyuanpei
Reprinted please indicate the source, Author: Qin Yuanpei, the source of this article: http://blog.csdn.net/qinyuanpei/article/details/25158323