C#中鼠标点击控制人物旋转
采用射线检测的方式,通过相机发射射线控制人物旋转
using UnityEngine;
using System.Collections;
public class PlayerRotation : MonoBehaviour
{
Quaternion targetRotation;
public float RotationSpeed = 25f;//旋转速度.
bool isRotation = false;//开始旋转.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//从摄像机的原点向鼠标点击的对象身上设法一条射线.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//当射线彭转到对象时.
if (Physics.Raycast(ray, out hit))
{
Debug.Log("发出射线");
// 目前场景中只有地形.
//判断一下当前射线碰撞到的对象是否为地形。
if (hit.collider.gameObject.tag == "Terrain")
{//设置地形Tag为Terrain.
//Debug.Log("射线碰撞到地形");
Vector3 targetPoint = Vector3.zero;//hitdist.point;
targetPoint.x = hit.point.x;
targetPoint.y = transform.position.y;
targetPoint.z = hit.point.z;
targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
isRotation = true;
}
}
}
//实际旋转.
if (isRotation)
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime * RotationSpeed);
}
}