第三人称控制
前言
经过一段时间的Unity 3D学习,练习制作了一个简单的游戏Demo。该Demo实现了一个简单的RPG副本,英雄杀死两种怪兽游戏即获胜。
该Demo使用Unity 3D的版本为 4.6.4f1。
游戏采用第三人称视角(3rd Person Controller),但是Standard Assert中的3rd Person Controller不能满足要求。因此,自己动手实现一个第三人称角色控制。下面将从角色(英雄)控制与Camera控制两方面介绍第三人称控制的实现。
英雄控制
旋转与移动
给英雄添加Character Controller组件。通过水平和垂直虚拟轴获取玩家输入,垂直虚拟轴控制前进后退,水平虚拟轴控制旋转(此过程也带动Camera绕英雄旋转)。只有当英雄在地上时方能操作,也就是controller.isGrounded==true
。
旋转的关键代码
//此段代码在英雄的脚本组件中
//获取水平虚拟轴输入
float horizontal = Input.GetAxis ("Horizontal");
float rotateY = horizontal * heroRotateSpeed; //英雄自转
float cameraRotateHero = horizontal * cameraRotateSpeed;//Camera绕英雄转
controller.transform.Rotate(0, rotateY*Time.deltaTime, 0); //人物调整朝向
mainCamera.transform.RotateAround(transform.position, Vector3.up,
cameraRotateHero * Time.deltaTime); //摄像机也旋转
移动的关键代码。首先根据输入,获得移动的本地方向向量,然后将其转为世界坐标系中的方向。
float vertical = Input.GetAxis("Vertical");
Vector3 targetDirection = new Vector3 (0.0f, 0.0f, vertical); //本地Z方向
if (targetDirection != Vector3.zero) {
targetDirection = targetDirection.normalized;
}
movingDirection = transform.TransformDirection (targetDirection) ; //向量变换self -> world
//...根据不同的操作设置移动速度movingSpeed,例如走、慢跑、快跑的速度是不同的
movingDirection *= movingSpeed;
if (Input.GetButton("Jump")) {
...}
movingDirection.y -= gravity * Time.deltaTime; //重力
if (movingDirection != Vector3.zero) {
collisionFlags = controller.Move (movingDirection * Time.deltaTime ); //当没有移动时,collisionFlags为None,所