需要安装一下cinemachine插件
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 用于控制anchor的位置
/// </summary>
public class CameraNew : MonoBehaviour
{
public Transform upleft;
public Transform downright;
public Transform anchor;
public CinemachineVirtualCamera CMvam1;
private float zoomMax =12;
private float zoomMin = 3;
private float zoomCurrent = 12.0f;
private float zoomSpeed = 2;
private bool bInTouch = false;
public bool camPanningUse = true;
private Vector3 anchorPosOld = Vector3.zero;
private Vector3 mousePosOld = Vector3.zero;
private Vector3 mousePosLast = Vector3.zero;
void Start()
{
CMvam1= (CinemachineVirtualCamera)Camera.main.GetComponent<CinemachineBrain>().ActiveVirtualCamera;
}
void Update()
{
//视角缩小
zoomCurrent -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
zoomCurrent = Mathf.Clamp(zoomCurrent, zoomMin, zoomMax);
CMvam1.m_Lens.OrthographicSize = zoomCurrent;
//拖动anchor,移动视窗
if (Input.GetMouseButton(0))
{
if (!bInTouch)
{
bInTouch = true;
mousePosOld = Input.mousePosition;
mousePosLast = Input.mousePosition;
anchorPosOld = anchor.transform.position;
}
else
{
mousePosLast = Input.mousePosition;
if (camPanningUse)
{
Vector3 vDelta = (Input.mousePosition - mousePosOld) * 0.008f;
Debug.Log("vDelta:" + vDelta);
Vector3 vForward = anchor.transform.forward; vForward.Normalize();
Debug.Log("vForward:" + vForward);
Vector3 vRight = anchor.transform.right; vRight.Normalize();
Debug.Log("vRight:" + vRight);
Vector3 vMove = -vForward * vDelta.y + -vRight * vDelta.x;
Debug.Log("vMove:" + vMove);
anchor.transform.position = anchorPosOld + new Vector3(vMove.x, vMove.z, anchor.transform.position.z);
}
}
}
}
public void InSide()
{
if (anchor.position.x < upleft.position.x)
{
anchor.position = new Vector3(upleft.position.x, anchor.position.y, anchor.position.z);
}
else if (anchor.position.x > downright.position.x)
{
anchor.position = new Vector3(downright.position.x, anchor.position.y, anchor.position.z);
}
if (anchor.position.y < upleft.position.y)
{
anchor.position = new Vector3(anchor.position.x, upleft.position.y, anchor.position.z);
}
else if (anchor.position.y > downright.position.y)
{
anchor.position = new Vector3(anchor.position.x, downright.position.y, anchor.position.z);
}
}
}
|