撰写了文章 发布于 2017-08-27 20:37:50
[Unity2D] 横版2D游戏开发实例五【完结】
例1 https://cowlevel.net/article/1904395
例2 https://cowlevel.net/article/1904819
例3 https://cowlevel.net/article/1905797
例4 https://cowlevel.net/article/1907211
时隔四部分,终于迎来了终章。这节的内容稍许会有些多,不过涉及到最难部分的动画逻辑理解好之后,剩余的部分也就是些代码的实现了,举一反三还是可以完成的。那么开始吧!
人物死亡
根据游戏规则,人物3点HP,3条命,当碰触一次敌人扣除一点血,3点血完毕跳转到LoadingScene,检测剩余命,当命>0,则重新回到场景,<0则回到标题菜单,状态重置。
死亡动画添加:Die,动画轨迹为人物先上升小幅高度后垂直下降到游戏画面之外Destroy,并配上受伤的状态Sprite。注意Die位于Damage图层,并设为优先度最高
添加Over Trigger,当Condition为Over时,AnyState切换为Die,取消HasExitTime,FixedDuration勾选动画变化。
在PlayerState脚本中添加对应代码如下:
void DecreaseHP(int i){
hp-=i;
if(hp<=0){
SendMessage("GameOver");//GameOver方法在MoveController脚本中实现
}
}
void LostLife(){
life-=1
}
在MoveController脚本中添加GameOver方法,具体代码如下
IEnumerator GameOver(){
GameState.gameOver=ture;
SendMessage("LostLife");
SendMessage("SaveAll");
animator.SetTrigger("Over");
yield return new WaitForSeconds(3f);
if(GameState*****<=0){
SceneManager.LoadScene(0);
}
else{
SceneManager.LoadScene(1);
}
}
此处使用IEnumerator类主要是为了调用yield方法实现等待后执行。
yield不可单独使用,需要与return配合使用,例如:
yield return WaitForSeconds(3.0); //等待3秒
yield return 1; //等1帧
所有使用yield的函数必须将返回值类型设置为IEnumerator类型
游戏状态存储及继承
为了能够在角色死亡之后重新读取角色的金币数等状态,我们通过单例模式,也即是public static 函数的形式来构建。为此我们新建一个空脚本,命名为GameInstance,并通过其中的状态来实现对金币、分数、声明这三个状态的实例化,代码如下
static class GameState{
public static bool gameOver=false;
public static int coins=0;
public static int score=0;
public static int life=5;
public static void Reset(){
gameOver=false;
coin=0;
score=0;
life=5;
}
}
在PlayerState脚本中添加对应代码
void SaveAll(){
GameState.coins=coins;
GameState.score=score;
GameState*****=life;
}
void LoadAll(){
coins=GameState.coins;
score=GameState.score;
life=GameState*****;
}
继续在MoveController脚本中添加GameState状态
void Awake(){
GameState.gameOver=false;
}
void FixedUpdate(){
if(GameState.gameOver){
body.velocity=Vector3.zero;
return;
}
}
重新切回Scene0,也就是我们的开始菜单,挂载脚本GameStart
void Start(){
GameState.Reset();
}
LoadingScene中回传游戏状态,并体现在UI上,故添加LoadingScene脚本
void Start(){
LoadValue();
}
void LoadValue(){//注意添加对应public Text属性
t_coins.text=GameState.coins+"";
t_score.text=GameState.score+"";
t_life.text=GameState.score+"";
}
游戏音效添加
音效添加这部分比较简单,就以动作音效为主进行操作,主要步骤如下:
为游戏添加组件AudioSource,脚本通过public AudioClip[] au生成数组,并在Inspector中添加对应的音频片段。之后通过如下代码实现
public AudioClip[] au;
public void SoundPlay(int id){
if(GetComponent<AudioSource>().isPlaying){return;}
GetComponent<AudioSource>().clip=au[id];
GetComponent<AudioSource>().Play();
}
之后可以在对应的触发逻辑处通过添加Camer.main.SendMessage("SoundPlay",4);的形式来实现播放。
文章所述的对应代码和组件我已上传,欢迎自行前往下载
链接: https://pan.baidu.com/s/1dFGQyAX 密码: uph9
那么,周末愉快!
目录
汪汪仙贝 1年前
万有引力之虹 [作者] 1年前
发布