1,首先创建一个人物,为人物添加角色控制器,可以在其中调节一些参数
2,创建一个相机,作为人物的子物体
3,为人物添加控制代码
3.1首先就是控制人物的行走代码:使用角色控制器中的Move方法来实现控制
float _horizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
if (player.isGrounded)
{
playerrun = new Vector3(_horizontal, 0, _vertical);
if (Input.GetKeyDown(KeyCode.Space)) //跳跃
playerrun.y = height;
}
playerrun.y -= g * Time.deltaTime; //添加重力,使用角色控制体组件时,刚体组件重力会不起作用
player.Move(player.transform.TransformDirection(playerrun * Time.deltaTime * speed)); //Move是角色控制器一种控制移动的方法
3.2然后是控制相机旋转的代码:
//使用鼠标来控制相机的视角的旋转
Cursor.lockState = CursorLockMode.Locked;//锁定指针到视图中心
Cursor.visible = false;//隐藏指针
x += Input.GetAxis("Mouse X");
y += Input.GetAxis("Mouse Y");
this.transform.eulerAngles = new Vector3(0, x, 0);
y = Mathf.Clamp(y, -45f, 45f); //限制相机在y轴上的旋转角度
camera.transform.eulerAngles = new Vector3(y, x, 0);
//让相机z轴保持不变,防止相机倾斜
if (camera.transform.localEulerAngles.z != 0)
{
float rotX = camera.transform.localEulerAngles.x;
float rotY = camera.transform.localEulerAngles.y;
camera.transform.localEulerAngles = new Vector3(rotX, rotY, 0);
}
最后将脚本赋予角色,然后将第一人称的相机拖入面板上
附上整个脚本的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class good : MonoBehaviour
{
CharacterController player; //定义角色控制器组件
public Transform camera; //第一人称相机
float speed = 2f;
float x, y; //相机旋转x,y轴控制
float g=10f; //重力
Vector3 playerrun; //控制玩家运动的向量
float height = 10f; //控制玩家跳跃的高度
// Use this for initialization
void Start()
{
player = this.GetComponent<CharacterController>();//获取人物的角色控制器组件
}
// Update is called once per frame
void Update()
{
//控制玩家运动
float _horizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
if (player.isGrounded)
{
playerrun = new Vector3(_horizontal, 0, _vertical);
if (Input.GetKeyDown(KeyCode.Space)) //跳跃
playerrun.y = height;
}
playerrun.y -= g * Time.deltaTime; //添加重力,使用角色控制体组件时,刚体组件重力会不起作用
player.Move(player.transform.TransformDirection(playerrun * Time.deltaTime * speed)); //Move是角色控制器一种控制移动的方法
//使用鼠标来控制相机的视角的旋转
Cursor.lockState = CursorLockMode.Locked;//锁定指针到视图中心
Cursor.visible = false;//隐藏指针
x += Input.GetAxis("Mouse X");
y += Input.GetAxis("Mouse Y");
this.transform.eulerAngles = new Vector3(0, x, 0);
y = Mathf.Clamp(y, -45f, 45f); //限制相机在y轴上的旋转角度
camera.transform.eulerAngles = new Vector3(y, x, 0);
//让相机z轴保持不变,防止相机倾斜
if (camera.transform.localEulerAngles.z != 0)
{
float rotX = camera.transform.localEulerAngles.x;
float rotY = camera.transform.localEulerAngles.y;
camera.transform.localEulerAngles = new Vector3(rotX, rotY, 0);
}
}
}