Unity简单的通过鼠标点击移动
Posted what-lee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity简单的通过鼠标点击移动相关的知识,希望对你有一定的参考价值。
public class PlayerController : MonoBehaviour { CharacterController cc; [SerializeField] float m_RotationSpeed = 10f; [SerializeField] private float speed = 10; Quaternion m_TargetDir; Vector3 targetPos = Vector3.zero; bool isRotated = false; void Start() { cc = GetComponent<CharacterController>(); } void Update() { if (Input.GetMouseButtonUp(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitinfo; if (Physics.Raycast(ray, out hitinfo)) { if (hitinfo.transform.CompareTag("Ground")) { targetPos = hitinfo.point; isRotated = false; m_RotationSpeed = 0; //对旋转速度初始,因为下边对这个值叠加了. Debug.DrawLine(Camera.main.transform.position, hitinfo.point, Color.red, 10); } } } if (!cc.isGrounded) { cc.Move((transform.position + new Vector3(0, -1000, 0)) - transform.position); } if (targetPos != Vector3.zero) { if (Vector3.Distance(targetPos, transform.position) > 0.1f) { Vector3 dir = (targetPos - transform.position).normalized; dir *= Time.deltaTime * speed; dir.y = 0; //免得脸朝地 if (!isRotated) { m_RotationSpeed += 5; //逐加旋转速度 m_TargetDir = Quaternion.LookRotation(dir); transform.rotation = Quaternion.Lerp(transform.rotation, m_TargetDir, m_RotationSpeed * Time.deltaTime); if (Quaternion.Angle(transform.rotation, m_TargetDir) < 1f) { m_RotationSpeed = 1; isRotated = true; } } cc.Move(dir); } } } }
以上是关于Unity简单的通过鼠标点击移动的主要内容,如果未能解决你的问题,请参考以下文章