Unity第一人称角色控制器
萌新一枚
通过Playercontroller .cs检测输入,在Playermoto.cs里写功能。
两个脚本都挂载到玩家身上,玩家需要添加角色控制器组件
新建一个空对象放置在角色底部用于检测地面,拖到Ground Check里
检测输入脚本——Playercontroller .cs
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
[RequireComponent(typeof(Playermoto))]//获取Playermoto脚本
public class Playercontroller : MonoBehaviour
{
// Start is called before the first frame update
public float mouseSensitivity = 10f;//鼠标灵敏度
public float groundDistance = 0.4f;
bool isGrounded;
public LayerMask groundMask;
public Transform groundCheck;
Playermoto motor;//Playermoto脚本
void Start()
{
motor = GetComponent<Playermoto>();//获取Playermoto组件
}
// Update is called once per frame
void Update()
{
//检测是否在地面
isGrounded = Physics.CheckSphere (groundCheck.position,groundDistance,groundMask);
float _xMov = Input.GetAxisRaw ("Horizontal");//获取水平方向
float _yMov = Input.GetAxisRaw ("Vertical");//获取垂直方向
//获取鼠标XY方向输入
float mouseX = Input.GetAxis ("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis ("Mouse Y") * mouseSensitivity * Time.deltaTime;
//检测跳跃和疾跑
bool jump = Input.GetButtonDown ("Jump");
bool run = Input.GetButton ("shift");
//执行Playermoto的函数
motor.move (_xMov,_yMov,isGrounded);
motor.freelook (mouseY,mouseX);
motor.jump (jump,isGrounded);
motor.run (run);
}
}
执行逻辑脚本——Playermoto.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Playermoto : MonoBehaviour
{
public CharacterController controller;
public Transform camera;
public Transform playerBody;
public Vector3 velocity = Vector3.zero;
public float gravity = -9.8f;//重力
public float speed = 5.0f;//速度
public float jumpfroce = 100f;//跳跃
float xRotation = 0f;
void Start ()
{
Cursor.lockState = CursorLockMode.Locked;//锁定光标
}
public void move(float _xMov, float _yMov ,bool isGrounded)//移动
{
if (isGrounded && velocity.y < 0)//判断是否在地面
{
velocity.y = -2f;
}
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _yMov;
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
controller.Move (_velocity * Time.deltaTime);//控制角色移动
velocity.y += gravity * Time.deltaTime;//重力
controller.Move (velocity * Time.deltaTime);
}
public void freelook (float mouseY,float mouseX)//鼠标控制视角
{
xRotation -= mouseY;
xRotation = Mathf.Clamp (xRotation, -90f, 90f);
camera.localRotation = Quaternion.Euler (xRotation,0f,0f);
playerBody.Rotate (Vector3.up*mouseX);
}
public void jump (bool jump,bool isGrounded)//跳跃
{
if(jump&&isGrounded == true)
{
velocity.y = Mathf.Sqrt (jumpfroce * -2f * gravity);
}
}
public void run (bool run)//疾跑
{
if (run == true)
{
speed = 20;
}
else
{
speed = 10;
}
}
}