01—创建工程
02—创建地面(Plane)和主角(Player),设置地面(Plane)长度和宽度(Scale中设置)
03—Assests目录下创建三个文件夹,Material(材质文件),Scripts(脚本文件),Prefab(预制体文件)
04—添加游戏物体(Food),调整Food高度和旋转(Transform,Rotation中设置)并拖动到Prefab文件中
05—创建墙体(Wall),设置长度与地面(Plan)长度一致
06—给游戏物体添加材质,Material文件夹中创建材质(Material)并调整好相机视野
07—Scripts文件中创建脚本Player,并添加到游戏物体Player上(控制游戏物体Player移动)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Rigidbody player_Rigidbody;
public int force = 5;
//游戏物体Score
public Text score_Text;
//游戏物体Win
public GameObject win_Text;
//当前分数
private int score = 0;
// Start is called before the first frame update
void Start()
{
//获得Player物体上的刚体组件
player_Rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//得到水平方向的值
float h = Input.GetAxis("Horizontal");
//得到垂直方向的值
float v = Input.GetAxis("Vertical");
//AddForce方法添加力
player_Rigidbody.AddForce(new Vector3(v, 0, -h) * force);
}
private void OnTriggerEnter(Collider other)
{
//判断触发物体标签是否为Food
if (other.gameObject.tag == "Food")
{
score++;
//销毁物体
Destroy(other.gameObject);
//将分数转化为string类型
score_Text.text = score.ToString();
//判断分数是否达到最大值
if (score == 11)
{
//SetActive方法显示游戏胜利UI
win_Text.SetActive(true);
}
}
}
}
08—Scripts文件中创建脚本Food(使Food围绕自身旋转)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Food : MonoBehaviour
{
private Transform food_Transform;
// Start is called before the first frame update
void Start()
{
//得到自身Transform组件
food_Transform = GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
//Rotate方法使自身围绕Y轴旋转
food_Transform.Rotate(new Vector3(0, 1, 0));
}
}
09—Prefab文件中设置Food预制体中的标签,设置为Food,并在Player脚本中实现Player接触后自身消失(代码在Player脚本中,有注释)
010—创建UI,Score和Win,并设置字体大小与颜色
011—Player脚本中实现游戏胜利和分数的判断,注意将Score与Win这两个游戏物体添加到Player脚本中
012—Scripts文件中创建Camera脚本,用来实现让相机(Main Camera)随时跟随Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
//取得player位置
public Transform player_Transform;
private Vector3 offest;
// Start is called before the first frame update
void Start()
{
//通过player位置减去相机自身位置,得到两个游戏物体之间的差值
offest = transform.position - player_Transform.position;
}
// Update is called once per frame
void Update()
{
//设置相机位置,使相机位置与player位置固定
transform.position = offest + player_Transform.position;
}
}
013—游戏完成,保存并发布