十主角脚本
10.1修改GameManager
首先修改GameManager脚本,为主角脚本做准备。
双击打开脚本编辑器,修改如下:
A添加2个变量:
//表示主角的生命值,也就是食物的总值
public int playerFoodPoints = 100;
//角色是否可以移动标志。特性HideInInspector表示此属性不会出现在Inspector窗口
[HideInInspector]
public bool playersTurn = true;
B 添加函数
//游戏结束
public void GameOver()
{
enabled =false;
}
10.2创建Player脚本
创建c#脚本修改名称为Player代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : MovingObject
{
//对内墙的破坏力
public int wallDamage = 1;
//食物增加生命
public int pointsPerFood = 10;
//苏打增加生命
public int pointsPerSoda = 20;
//重启延迟时间
public float restartLevelDelay = 1f;
//Player动画
private Animator animator;
//当前生命值
private int food ;
protected override void Start ()
{
animator = GetComponent<Animator>();
food = GameManager.instance.playerFoodPoints;
base.Start();
}
void Update ()
{
if(!GameManager.instance.playersTurn)
return ;
//键盘输入,控制角色移动。
int horizontal = 0;
int vertical = 0 ;
horizontal = (int)Input.GetAxisRaw("Horizontal");
vertical = (int)Input.GetAxisRaw("Vertical");
if(horizontal!=0)
vertical = 0;
if(horizontal!=0 || vertical!=0)
AttemptMove<Wall>(horizontal,vertical);
}
//内置函数
private void OnDisable()
{
GameManager.instance.playerFoodPoints = food;
}
protected override void AttemptMove<T>(int xDir,int yDir)
{
//没移动一次食物减少1
food--;
base.AttemptMove<T>(xDir,yDir);
GameManager.instance.playersTurn =false;
}
//检查是否游戏结束
private void CheckIfGameOver()
{
//当前生命低于0游戏结束
if(food <= 0 )
{
GameManager.instance.GameOver();
}
}
//碰撞内墙
protected override void OnCantMove<T>(T component)
{
Wall hitWall = component as Wall;
//破坏内墙
hitWall.DamageWall(wallDamage);
//出发PlayerChop触发器
animator.SetTrigger("PlayerChop");
}
//主角移动套exit的时候,加载下一关
private void Restart()
{
Application.LoadLevel(Application.loadedLevel);
}
//主角被敌人攻击的时候损失生命值
public void LoseFood(int loss)
{
//出发PlayerHit触发器
animator.SetTrigger("PlayerHit");
food -= loss;
CheckIfGameOver();
}
//检查碰撞,exit,food,soda
private void OnTriggerEnter2D(Collider2D other)
{
//主角移动到出口
if(other.tag == "Exit")
{
Invoke("Restart",restartLevelDelay);
enabled = false;
}
//吃掉食物
else if(other.tag == "Food")
{
food += pointsPerFood;
other.gameObject.SetActive(false);
}
//喝掉苏打汽水
else if(other.tag == "Soda")
{
food += pointsPerSoda;
other.gameObject.SetActive(false);
}
}
}
保存代码后,切换到Hierarchy窗口,把Player.cs作为组件附加给Player预制体。
切换Inspector窗口,给Blocking Layer复制为BlockingLayer。