[RequireComponent(typeof(Camera))]
public class UECamera : MonoBehaviour
{
bool draging;
float fpsYaw;
float fpsPitch;
float yaw;
Quaternion rotation = Quaternion.identity;
const int MoveButton = 0;
const int AngleButton = 1;
const float ForwardScale = 15f;
const float MoveScale = 5f;
const float YawScale = 30f;
const float FPYawScale = 50f;
const float FPPitchScale = 50f;
private void Awake()
{
fpsYaw = transform.localEulerAngles.y;
fpsPitch = transform.localEulerAngles.x;
}
// 虚幻4风格相机控制
// 鼠标左键左右拖动:左右旋转视角
// 鼠标左键上下拖动:前后移动
// 鼠标右键拖动:第一人称查看
// 鼠标左右键拖动:上下左右平移
private void LateUpdate()
{
if(GUIUtility.hotControl != 0 || (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject()))
{
return;
}
if(!draging && (Input.GetMouseButton(MoveButton) || Input.GetMouseButton(AngleButton)))
{
draging = true;
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
if(draging)
{
float x = Input.GetAxisRaw("Mouse X");
float y = Input.GetAxisRaw("Mouse Y");
if (Input.GetMouseButton(MoveButton))
{
if(Input.GetMouseButton(AngleButton))
{
Vector3 right = rotation * Vector3.right;
transform.localPosition += right * x * Time.deltaTime * MoveScale;
transform.localPosition += Vector3.up * y * Time.deltaTime * MoveScale;
}
else
{
yaw += x * Time.deltaTime * YawScale;
Quaternion yawRot = Quaternion.AngleAxis(yaw + fpsYaw, Vector3.up);
rotation = (yawRot * Quaternion.AngleAxis(fpsPitch, Vector3.right));
transform.localPosition += (yawRot * Vector3.forward) * y * Time.deltaTime * ForwardScale;
}
}
else if(Input.GetMouseButton(AngleButton))
{
fpsYaw += x * Time.deltaTime * FPYawScale;
fpsPitch -= y * Time.deltaTime * FPPitchScale;
rotation = Quaternion.AngleAxis(fpsYaw + yaw, Vector3.up) * Quaternion.AngleAxis(fpsPitch, Vector3.right);
}
transform.localRotation = rotation;
}
if(draging && (Input.GetMouseButtonUp(MoveButton) || Input.GetMouseButtonUp(AngleButton)))
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
draging = false;
}
}
}
unity脚本实现虚幻4风格相机控制
80行代码做一个虚幻4样式相机控制,调试游戏用
暂无关于此日志的评论。