Unity3D——物体鼠标跟随转向

时间:2024-09-19 21:08:08

int floorMask;
float camRayLenth = 100f;//摄像机射线距离

void Truning()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//根据当前鼠标的位置,发射一条射线
RaycastHit hit;
if (Physics.Raycast(ray, out hit, camRayLenth, floorMask))//判断是否发出的射线产生碰撞
{
Vector3 playerToMouse = hit.point - transform.position;//获取鼠标到碰撞点的向量
playerToMouse.y = 0f;
Quaternion ratation = Quaternion.LookRotation(playerToMouse);//设置转角
GetComponent<Rigidbody>().MoveRotation(ratation);

}
}