该感谢分享:具体实现看第一第三人称控制器
private void CameraOcclusion()
{
Vector3 CameraPointing = transform.position - MainCameraModel.transform.position;//相机到人物的向量
Ray CameraRay = new Ray(MainCameraModel.transform.position, CameraPointing);
RaycastHit hitInfo;
if (Physics.Raycast(CameraRay, out hitInfo))
{
if (hitInfo.collider.tag != "Player")
{
_mesList.Add(hitInfo.collider.gameObject.GetComponent<MeshRenderer>());
hitInfo.collider.gameObject.GetComponent<MeshRenderer>().enabled = false;
}
else
{
foreach (var item in _mesList)
{
item.enabled = true;
}
_mesList.Clear();
}
}
}
/// <summary>
/// 运动
/// </summary>
private void Move()
{
WalkingSpeed = Input.GetKey(KeyCode.LeftShift) ? RunningSpeed : 2.0f;//加速
if (GroundCheck)//跳跃
{
_Dontjump = Input.GetKeyDown(KeyCode.Space) ? JunpHeiqht : _Dontjump;
GroundCheck = false;
}
if (_characterController.isGrounded)
{
GroundCheck = true;
}
float _hprizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
_moveDirection = new Vector3(_hprizontal * WalkingSpeed, _Dontjump, _vertical * WalkingSpeed);
_moveDirection = transform.TransformDirection(_moveDirection);
_Dontjump += Gravity * Time.deltaTime;//重力
_characterController.Move(_moveDirection * Time.deltaTime);
Vector3 _movement = Vector3.zero;
_movement = transform.forward * _vertical + transform.right * _hprizontal;
_isKeyboard = _movement == Vector3.zero ? _isKeyboard : true;//判断是否有按键输入
if (_isKeyboard && !FirstPersonExchange)//人物自身旋转
{
transform.rotation = Quaternion.Slerp(transform.rotation, CameraFather.transform.rotation, 0.15f);
Quaternion PlayerModelsRotation = Quaternion.LookRotation(_movement);
PlayerModelsTransform.rotation = Quaternion.Lerp(PlayerModelsTransform.rotation, PlayerModelsRotation, Time.deltaTime * PlayerRotationSpeed);
_isKeyboard = false;
}
}