[Unity] FlappyBird profiling-source code

Source: Internet
Author: User

FlappyBird is an extremely simple but very popular game. After learning about this crazy game, I had an impulse to reproduce it. It took me more than four hours to generate a playable version, share with you (the download link at the end of the article ).

The following is a brief introduction to the development process of the game (this example needs to be opened in unity4.3.0 or later versions ).

Directory description runtime diagram:
The directory structure of the project is as follows: anims stores animation resources, prefab stores preset objects, scprits stores scripts, and sprites stores textures.
Prepare resources to obtain FlappyBird's texture resources and sound effects resources. Import the resource to the sprites folder, select atlas, and edit it in Inspector, as shown in:
Set to sprite and the mode to Multiple. Click the Sprite Editor to separate the corresponding images. In the displayed dialog box, you can use the automatic graph cutting method, for example:
Next, we can encode the scenes. In order to distinguish the layers of the scenes (mainly used to determine the order of layers, sorting Layer function) and coding requirements, we can establish some tag sorting layers and layers. Click the Layers drop-down menu in the upper-right corner of the Unity editor and select "Edit Layers...". For example, enter the following information:
There are two obstacles to moving roads and one obstacle Road (for example). Two Roads are used in the scenario to loop repeatedly (when one road moves out of the screen, the position is adjusted again, wait for the next time to appear on the screen) to keep moving.
Below is part of the road movement code road. cs
Public class road: MonoBehaviour {.... // Update is called once per framevoid Update () {Vector3 pos = trans. position; pos. x-= speed * Time. deltaTime; trans. position = pos; if (pos. x <=-1.6f-3.35f * idx) {// when the road is removed from the screen, adjust its position from a small value. Vector3 pp = roads [idx % 2]. transform. position; pp. x + = 3.35f; idx ++; roads [idx % 2]. transform. position = pp; if (isBegin) {roads [idx % 2]. getComponent <roadGen> (). gen ();}}}

Road barrier display or not (on the welcome page, the road does not need barrier), and the barrier is born in the documents roadGen. in cs, I merge the upper and lower columns into an object. When generating obstacles, I only need to move them up and down within a certain range. The code snippet is as follows:
Public class roadGen: MonoBehaviour {public GameObject [] zhuzi; public float down = 3.8f, upper = 6.0f ;... public void gen () {// a road has two pillars, zhuzi [0]. setActive (true); zhuzi [1]. setActive (true); Vector3 p = zhuzi [0]. transform. localPosition; float vv = Random. value; p. y = Mathf. lerp (down, upper, vv); zhuzi [0]. transform. localPosition = p; // set the position of the first column p = zhuzi [1]. transform. localPosition; vv = Random. value; p. y = Mathf. lerp (down, upper, vv); zhuzi [1]. transform. localPosition = p; // set the position of the second pillar} public void hidden () {zhuzi [0]. setActive (false); zhuzi [1]. setActive (false );}}
Finally, BoxCollider2D is added to both the obstacle and the ground to obtain the collision message.
Birds with big lips first have a flying Frame Animation. In atlas under the sprite folder, select three frames and drag them directly to the scene, unity automatically forms a sprite with a frame animation. Select the sprite and adjust the playing time of the sprite on the Window/Animation interface, for example:
Similarly, a Component of BoxCollider2D is required for the bird to respond to the collision, and Rigibody2D must be added. For more information, see examples. There will be two scripts involved here (in a rush of time, there is no need to consider the design): bird. cs and clider. cs; the former is used to apply force to the bird, and the latter handles collision. The most important part of this game is clider. cs. The file processing score and whether it hits the obstacle. The Code is as follows:
using UnityEngine;using System.Collections;public class clider : MonoBehaviour {public score s;public int clideNum;public string tag;public bool isSuccess = false, isFail = false;// Use this for initializationvoid Start () {s = GameObject.Find("score").GetComponent<score>();clideNum = 0;tag = "";isSuccess = false;isFail = false;}// Update is called once per framevoid Update () {}void OnTriggerEnter2D(Collider2D other) {if(other.gameObject.tag.Equals("success")) {if(!isSuccess) {print("===trigger enter==");isSuccess = true;s.success();print ("success");}} else if(!isFail) {print("===trigger enter==");isFail = true;s.fail();print ("fail");}}void OnTriggerExit2D(Collider2D other) {print("===trigger exit==");isSuccess = false;}void OnCollisionEnter2D(Collision2D other) { if(other.gameObject.tag.Equals("success")) {if(!isSuccess) {print("===collision enter==");isSuccess = true;s.success();}} else if(!isFail) {print("===collision enter==");isFail = true;s.fail();}}void OnCollisionExit2D(Collision2D coll) {print("===collision exit==");isSuccess = false;}public void reset() {isSuccess = false;isFail = false;}}
Welcome Page welcome page has a bird animation, and can respond to the touch and start the game (implemented in isReady. cs ). The Animation of the bird is the process of swinging up and down. Select the bird and add the Position attribute on the Animation interface and adjust it as follows:
The isReady. cs code is as follows:
Public class isReady: MonoBehaviour {public GameObject road, bird; // Use this for initialization void Start () {}// Update is called once per frame void Update () {if (Input. getButtonDown ("Fire1") {// after you touch the screen, the game begins. setActive (false); road. getComponent <road> (). isBegin = true; bird. getComponent <Rigidbody2D> (). isKinematic = false; // welcome page. Set this parameter to true so that the bird does not respond to gravity. Set this parameter to false after the start. getComponent <Animator> (). enabled = false ;}}}


The settlement page begins to hide the game. After the user loses the game, an animation is played and displayed. When the user clicks the play button, the game is reset to the welcome page. The settlement page involves the script restart. when the game is reset in cs, the BroadcastMessage technology is used to find all objects whose tags are needReset, and call the reset function in the code of itself and sub-objects to reset the game. The Code is as follows:
Public class restart: MonoBehaviour {public Camera cam2d; public GameObject ready; void Update () {if (Input. getButtonDown ("Fire1") {Collider2D h = Physics2D. overlapPoint (cam2d. screenToWorldPoint (Input. mousePosition), (1 <LayerMask. nameToLayer ("btn"); if (h) {// if you click the play button gameObject. setActive (false); Time. timeScale = 1; ready. setActive (true); GameObject [] resets = GameObject. findGameObjectsWithTag ("needReset"); // query all objects whose tags are needReset foreach (GameObject r in resets) {r. broadcastMessage ("reset"); // call the reset function in the code of itself and its sub-objects to reset the game }}}}


For usage of Physics2D. OverlapPoint, refer to the second point in the [Unity] skill set.
Add audio To be continued...

Disclaimer: The resources referenced in this article come from the Internet and are only for learning purposes. Do not commercialize them.

: Http://download.csdn.net/detail/stalendp/6914227

Apk download link: http://pan.baidu.com/s/1c09rKMc

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.