注1:在此工程中,我用的为此版本
注2:在此项目中,我从UnityStore导入一个可行移动的模型之后,发现其中有材质丢失和包依赖丢失的问题。导致每次导入工程时,都需要重新导入一遍。
一、实现目标
实现简单的人物移动加上视角切换,为创建的capsule实现操纵WASD的前后左右移动,并且可以通过按钮点击实现第一人称到第三人称的视角切换。
此处会联系到前文:
二、实现方法
第一步:创建capsule,命名为PersonCapsule,并未其添加两个相机,分别命名为TheFirstPersonCamera,TheThirdPersonCamera。
第二步:创建脚本 -- PersonMoving,按如下编辑:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// version - 0.1
/// 用于人物的前后移动与左右视角的旋转。
/// </summary>
public class PersonMoving : MonoBehaviour
{
public float Currentspeed = 10;
private float InterSpeed = 10;
public float mouseSensitivity = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Debug.Log("h is:" + h + " v is:" + v);
transform.Translate(h * Currentspeed * Time.deltaTime,0, v * Currentspeed * Time.deltaTime);
float mousex = Input.GetAxis("Mouse X") * mouseSensitivity;
//float mousey = Input.GetAxis("Mouse Y") * mouseSensitivity;
if (Input.GetMouseButton(1)) // 鼠标右键旋转视角
{
//transform.Rotate(0, 0, mousey); // 旋转Y轴
transform.Rotate(0, mousex, 0, Space.World); // 旋转X轴
}
//加速
if (Input.GetKeyDown(KeyCode.LeftShift))
{
Currentspeed = Currentspeed * 5;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
Currentspeed = InterSpeed;
}
}
}
第三步:将脚本连接到PersonCapsule
第四步:编写脚本 -- TheThirdPersonCameraSelected
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///
/// version - 0.1
/// 点击Button切换到第三人称相机
/// </summary>
public class TheThirdPersonCameraSelected : MonoBehaviour
{
public Camera godviewcamera;
public Camera freecamera;
public Camera firstpersoncamera;
public Camera ThirdPersonCamera;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void TheThirdPersonCameraSelectedF()
{
godviewcamera.gameObject.SetActive(false);
freecamera.gameObject.SetActive(false);
firstpersoncamera.gameObject.SetActive(false);
ThirdPersonCamera.gameObject.SetActive(true);
}
}
第五步:将脚本TheThirdPersonCameraSelected连接到第一步中创建的TheThirdPersonCamera上将对应的相机拖到相应的位置。
第六步:创建一个Button -- TheThirdPersonCameraButton,为其添加OnClick()事件。
三、结果测试
点击”第三人称“按钮,跳转到第三人称相机。