/// <summary> 鼠标点击的目标位置 </summary>
Vector3 m_targetPos;
/// <summary> 人物移动速度 </summary>
float m_Speed = 10f;
/// <summary> 人物控制器 </summary>
CharacterController m_CharacterController;
/// <summary> 目标向量 </summary>
Quaternion m_targetQuaternion;
/// <summary> 旋转速度 </summary>
float m_quaternionSpeed = 5f;
/// <summary> 是否旋转结束 </summary>
bool isRotationOver;
void Start()
{
m_CharacterController = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out (hit)))
{
if (hit.collider.gameObject.name == "Ground")
{
m_targetPos = hit.point;
isRotationOver = false;
}
}
}
//让角色贴着地面,是否接地,没有接地的话让它迅速移动到地面
if (!m_CharacterController.isGrounded)
{
m_CharacterController.Move(transform.position + new Vector3(0, -1000, 0) - transform.position);
}
//角色转身以及移动
if (m_targetPos != Vector3.zero)
{
Vector3 direction = m_targetPos - transform.position;
direction = direction.normalized;//归一化(我们让人物以匀速前进,如果不归一化那么会出现距离越长速度越快的现象,我们要的向量仅仅决定方向,不能影响其他值)
direction = direction * Time.deltaTime * m_Speed;
direction.y = 0;
//让角色缓慢转身
if (!isRotationOver)
{
#region 方法一:比较死板的转向,速度很快,没有较好的视觉效果
//transform.LookAt(new Vector3(m_targetPos.x, transform.position.y, m_targetPos.z));
#endregion
#region 方法二:缓慢转向,视觉效果比较真实
m_targetQuaternion = Quaternion.LookRotation(direction);//旋转的方向
transform.rotation = Quaternion.Lerp(transform.rotation, m_targetQuaternion, Time.deltaTime * m_quaternionSpeed);
#endregion
//转身完毕
if (Quaternion.Angle(m_targetQuaternion, transform.rotation) < 1)
{
isRotationOver = true;
}
}
m_CharacterController.Move(direction);
}
}
Unity实现点击屏幕移动人物
最新推荐文章于 2023-07-31 14:03:00 发布