using UnityEngine;
namespace ZFramework
{
///
/// 用户基类
///
[RequireComponent(typeof(CharacterController))]
public class PlayerBase : MonoBehaviour
{
///
/// 角色控制器
///
CharacterController characterController;
///
/// 方向
///
Vector3 direction;
///
/// 移动速度
///
[SerializeField] protected float moveSpeed = 5;
///
/// 跳跃高度
///
protected float jumpPower = 5;
///
/// 重力
///
[SerializeField] protected float gravity = 9.8f;
///
/// 旋转速度
///
protected float mouseSpeed = 5;
///
/// 最小视角角度
///
protected float minmouseY = -45;
///
/// 最大视角角度
///
protected float maxmouseY = 45;
///
/// 是否能移动
///
[SerializeField] protected bool isCanMove = true;
///
/// 是否能旋转
///
[SerializeField] protected bool isCanRotate = true;
///
/// 是否能跳跃
///
[SerializeField] protected bool isCanJump = true;
///
/// 是否暂停玩家操控
///
private bool isPause;
float RotationY = 0f;
float RotationX = 0f;
///
/// 摄像机(用户视角)
///
private Transform mainCamera;
float _horizontal;
float _vertical;
private void Awake()
{
OnAwake();
}
private void FixedUpdate()
{
if (isPause) return;
_horizontal = Input.GetAxis("Horizontal");
_vertical = Input.GetAxis("Vertical");
OnFixedUpdate();
}
public virtual void OnAwake()
{
isPause = false;
characterController = GetComponent();
mainCamera = transform.Find("MainCamera");
if (mainCamera == null) Debug.LogError("transform find not have mainCamera! please check!");
}
public virtual void OnFixedUpdate()
{
PlayerMove();
CameraRotate();
}
///
/// 暂停玩家控制(此处的暂停包括玩家的所有控制)
///
public virtual void Pause()
{
isPause = true;
}
///
/// 恢复玩家控制(此处的暂停包括玩家的所有控制)
///
public virtual void Resume()
{
isPause = false;
}
///
/// 用户移动控制
///
void PlayerMove()
{
if (isCanMove)
{
if (characterController.isGrounded)
{
direction = new Vector3(_horizontal, 0, _vertical);
if (Input.GetKeyDown(KeyCode.Space) && isCanJump)
direction.y = jumpPower;
}
direction.y -= gravity * Time.deltaTime;
characterController.Move(
characterController.transform.TransformDirection(direction * Time.deltaTime * moveSpeed));
}
}
///
/// 相机旋转视角控制
///
void CameraRotate()
{
if (isCanRotate)
{
if (Input.GetMouseButton(1))
{
RotationX += mainCamera.transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSpeed;
RotationY -= Input.GetAxis("Mouse Y") * mouseSpeed;
RotationY = Mathf.Clamp(RotationY, minmouseY, maxmouseY);
this.transform.eulerAngles = new Vector3(0, RotationX, 0);
mainCamera.transform.eulerAngles = new Vector3(RotationY, RotationX, 0);
}
}
}
}
}