本文实例为大家分享了Unity3d实现Flappy Bird的具体代码,供大家参考,具体内容如下
一、小鸟
在游戏中,小鸟并不做水平位移,而是通过障碍物的移动让小鸟有水平运动的感觉,小鸟只需要对鼠标的点击调整竖直加速度就可以了,同时加上水平旋转模仿原版的FlappyBird的运动。同时,还要对竖直位置进行判断,否则游戏不能正常结束。
这里贴上小鸟上附加的脚本代码
Player.cs
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private Rigidbody body;
public Vector3 jumpForce = new Vector3(0, 300, 0);
private bool state = true; //确保只执行一次
private int bestScore = 0;
// Use this for initialization
void Start () {
body = transform.GetComponent<Rigidbody>();
}
void OnCollisionEnter(Collision collisionInfo)
{
if (state)
{
//碰撞游戏结束
state = false;
Score.instance.state = false;
AudioManager.instance.PlayHit();
AudioManager.instance.PlayDie();
Invoke("EndGame", 0.4f);
}
}
// Update is called once per frame
void Update ()
{
//下限
if (transform.position.y < -20)
{
if (state)
{
state = false;
Score.instance.state = false;
AudioManager.instance.PlayDie();
Invoke("EndGame", 0.4f);
}
}
//上限
if (transform.position.y > 20)
{
if (state)
{
state = false;
Score.instance.state = false;
AudioManager.instance.PlayDie();
Invoke("EndGame", 0.4f);
}
}
//判断鼠标左键点击或者空格
if (Input.GetKeyDown(KeyCode.Space)||Input.GetMouseButtonDown(0))
{
AudioManager.instance.PlayFly();
body.velocity = Vector3.zero;
//加速度
body.AddForce(jumpForce);
//控制旋转量
this.transform.rotation = Quaternion.Euler(45, 270, 0);
}
else
{
//旋转
if (transform.rotation.eulerAngles.x >= 280||transform.rotation.eulerAngles.x<=50)
{
transform.Rotate(-150 * Time.deltaTime, 0, 0);
}
}
}
public void EndGame()
{
//保存最佳成绩
PlayerPrefs.SetInt("PlayerScore", Score.instance.score);
bestScore = PlayerPrefs.GetInt("PlayerBestScore");
if (Score.instance.score > bestScore)
bestScore = Score.instance.score;
PlayerPrefs.SetInt("PlayerBestScore", bestScore);
//跳转到结束场景
Application.LoadLevel("End");
}
}










