经验:所有第一次运行可以,下一次不行的都是因为某个判断值不重新归位
//===================================================
//作者:
//悠长de小巷
//创建时间:
//2018-01-27 15:04:19
//===================================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoleCtrl : MonoBehaviour
{
/// <summary>
/// 移动的目标点
/// </summary>
private Vector3 m_TargetPos=Vector3.zero;
private CharacterController m_CharacterController;
/// <summary>
/// 移动速度
/// </summary>
[SerializeField]//可以显示在UI修改
private float m_Speed=10f;
/// <summary>
/// 转身速度
/// </summary>
private float m_RotationSpeed = 0.2f;
/// <summary>
/// 转身方向
/// </summary>
private Quaternion m_TargetQuaternion;
/// <summary>
/// 是否转身完成
/// </summary>
private bool m_RotationOver = false;
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
}
private void Update()
{
if (m_CharacterController == null) return;
if (Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.gameObject.name.Equals("Plane", System.StringComparison.CurrentCultureIgnoreCase))
{
m_TargetPos = hitInfo.point;
m_RotationOver = false;
m_RotationSpeed = 0;
}
}
}
//让角色到地面
if (!m_CharacterController.isGrounded)
{
m_CharacterController.Move((transform.position+new Vector3(0,-1000,0))-transform.position);//
}
if (m_TargetPos != Vector3.zero)
{
//Debug.DrawLine(Camera.main.transform.position, m_TargetPos);
if (Vector3.Distance(m_TargetPos, transform.position) > 0.1f)
{
//transform.LookAt(m_TargetPos);
//transform.Translate(Vector3.forward * Time.deltaTime * m_Speed);
Vector3 direction = m_TargetPos - transform.position;
direction = direction.normalized;//归一化
direction = direction * Time.deltaTime * m_Speed;
direction.y = 0;//设置追随目标的y值为0
//transform.LookAt(new Vector3(m_TargetPos.x, transform.position.y, m_TargetPos.z));正常但无差值旋转
//transform.LookAt(m_TargetPos); //会出现y轴旋转
//让角色缓慢转身
//差值方法1:
if (!m_RotationOver)
{
m_RotationSpeed += 5f;
m_TargetQuaternion = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Lerp(transform.rotation, m_TargetQuaternion, Time.deltaTime * m_RotationSpeed);
if (Quaternion.Angle(m_TargetQuaternion, transform.rotation) < 0.1f)
{
m_RotationSpeed = 1;
m_RotationOver = true;
}
}
//差值方法2:效果差
//if(m_RotationSpeed<=1)
//{
// m_RotationSpeed +=50f * Time.deltaTime;
// Debug.LogError(m_RotationSpeed);
// m_TargetQuaternion = Quaternion.LookRotation(direction);
// transform.rotation = Quaternion.Lerp(transform.rotation, m_TargetQuaternion, Time.deltaTime * m_RotationSpeed);
//}
m_CharacterController.Move(direction);
}
}
}
}