一. 初始设置
1. 创建3D项目
2. 项目创建后会自带一个SamleScene并自动引入一些基础包,重新Save as一个新场景MainGame
新建场景都默认有天空盒和平行光源模拟太阳光,对应场景中的默认对象Main Camera和Directional Light
3. 场景中新建平面
重命名为Ground:
选中对象后f键可以定位到对象,关闭网格显示:
使用缩放工具改变plane大小和角度:
4.新建球体sphere, 重命名为player,
sphere, cube等unity预制对象都有标准的尺寸,把player对象y轴设置为0.5,正好贴地
5. 改变游戏对象颜色
首先新建材质文件夹
新建BackGroud材质并设置RGB
把材质托到游戏对象上就可以改变对象的材质,这里拖到plane上面
6. 把光源的Rotation的Y改为60,提升光源效果
二. 移动Player
1. 给player添加刚体组件
2.新建脚本文件夹Scripts
新建C#脚本PlayController,关联到Player对象,移动到Scripts目录下
继承自MonoBehaviour类,使用Start方法会在脚本激活的第一帧被调用,使用Update方法在每一帧展示前被调用,而FixedUpdate是在任何物理计算之前被调用,所以这里使用FixedUpdate,player移动源码:
using UnityEngine;
public class PlayController : MonoBehaviour
{
private Rigidbody rb;
public float speed;//加力速度
private void Start()
{
rb = GetComponent<Rigidbody>();//获取刚体组件
}
// Update is called once per frame
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");//键盘水平移动获取
float moveVertical = Input.GetAxis("Vertical");//键盘垂直移动获取
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);//刚体加力
}
}
三. 移动摄像机
1. 设置camera的y轴高度为10,x轴旋转45度,放到一个合适的摄像头位置
2. 为camera新建一个脚本控制视角移动
using UnityEngine;
public class CameraController : MonoBehaviour
{
public GameObject player;//表示球体
public Vector3 offset;//视角偏移量
void Start()
{
offset = transform.position - player.transform.position;//固定初始偏移量
}
void LateUpdate()//和update一样每帧执行,但会在所有游戏对象update执行完毕后执行,所以这里用它
{
transform.position = player.transform.position + offset;//每一帧偏移量不变修正
}
}
把该脚本挂载到camera对象下,同时设置好player即可:
四. 设置游戏场地
1. 新建一个空的游戏对象为四面墙的父对象
2. 依次创建4个立方体,调整大小和位置,成为四面墙(使用duplicate快速创建).