您的位置:首页 > 移动开发 > Unity3D

unity3d fpscontrol中mouselook脚本的解释

2016-12-20 22:54 411 查看
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

namespace UnityStandardAssets.Characters.FirstPerson
{
[Serializable]
public class MouseLook
{
public float XSensitivity = 2f;//x轴旋转的灵敏度
public float YSensitivity = 2f;//y轴旋转的灵敏度
public bool clampVerticalRotation = true;//垂面的差值
public float MinimumX = -90F;//摄像机旋转范围
public float MaximumX = 90F;//摄像机旋转范围
public bool smooth;//是否开启平滑
public float smoothTime = 5f;//平滑时间控制

private Quaternion m_CharacterTargetRot;//角色目标旋转方向
private Quaternion m_CameraTargetRot;//相机目标旋转方向

//初始化
public void Init(Transform character, Transform camera)
{
m_CharacterTargetRot = character.loc
4000
alRotation;
m_CameraTargetRot = camera.localRotation;
}

//鼠标控制视角
public void LookRotation(Transform character, Transform camera)
{
//rot=鼠标轴向值*轴向灵敏度
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;
//角色转动方向为y轴,yrot为y轴旋转数值。(向左向右看的时候只能转身子)
m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
//相机转动方向为x轴,xrot为x轴旋转数值。加负号为了调整旋转方向
m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f);
//垂面的旋转限制在 MinimumX 和MaximumX之间
if(clampVerticalRotation)
m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);
//平滑处理
if(smooth)//如果开启了平滑处理
{
//利用球形差值进行平滑缓冲
character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
smoothTime * Time.deltaTime);
camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
smoothTime * Time.deltaTime);
}
else
{
//如果没有平滑就赋值
character.localRotation = m_CharacterTargetRot;
camera.localRotation = m_CameraTargetRot;
}
}

//旋转轴差值函数
Quaternion ClampRotationAroundXAxis(Quaternion q)
{
q.x /= q.w;//将四元数中的x    x*sin(角度/2)转化为x*tan(角度/2)
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;
//Atan将返回弧度,Rad2Deg将弧度数转化为角度数,得出旋转角
float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x);
//clamp函数
/*
clamp(22,4,6)
返回 6,因为 22 大于 6 而 6 是范围的最大数值。

clamp(2,4,6)
返回 4,因为 2 小于 4 而 4 是范围的最小数值。

clamp(5,4,6)
返回 5,因为该数值位于范围内。

*/
//如果旋转角度超过范围,将其限制在范围内
angleX = Mathf.Clamp (angleX, MinimumX, MaximumX);
//赋值四元数q中x的值
q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX);

return q;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d 脚本