鼠标控制相机 上下左右缩放 代码
工作中用在 Tilemap 里面的代码
using UnityEngine;
using UnityEngine.Tilemaps;
/*************************************************************
* 场景相关
*************************************************************/
public class TileCamera
{
public static bool isMove = false;
/// <summary>
/// 获取屏幕中心的瓦块坐标
/// </summary>
/// <returns></returns>
public static Vector3Int GetScreenCentreCellPos(Camera TilemapCamera, Tilemap GoodsLayer)
{
Vector3 center = TilemapCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
Vector3Int CentreCellPos = GoodsLayer.WorldToCell(center);
return CentreCellPos;
}
/// <summary>
/// 场景移动
/// </summary>
public static void MoveView(Camera TilemapCamera)
{
//开启左右移动
if (Input.GetMouseButtonDown(1))
isMove = true;
if (Input.GetMouseButtonUp(1))
isMove = false;
if (isMove)
{
Vector3 pos = TilemapCamera.ScreenToWorldPoint(Input.mousePosition);
Debug.Log(pos);
//限制超出屏幕
if (pos.x < -20)
pos.x = -20;
else if (pos.x > 20)
pos.x = 20;
//上下移动
if (pos.y > 19)
pos.y = 19;
else if (pos.y < 1)
pos.y = 1;
TilemapCamera.transform.position = new Vector3(Mathf.Lerp(TilemapCamera.transform.position.x, pos.x, 1.5f * Time.deltaTime), Mathf.Lerp(TilemapCamera.transform.position.y, pos.y, 1.5f * Time.deltaTime), pos.z);
}
}
/// <summary>
/// 处理视野的拉近和拉远效果
/// </summary>
public static void ScrollView(Camera TilemapCamera)
{
//print(Input.GetAxis("Mouse ScrollWheel")); //鼠标向后滑动返回负数(拉近视野),向前正数(拉远视野)
if(TilemapCamera!=null)
{
TilemapCamera.orthographicSize += Input.GetAxis("Mouse ScrollWheel");
if (TilemapCamera.orthographicSize < 2)
{
TilemapCamera.orthographicSize = 2;
}
else if (TilemapCamera.orthographicSize > 20)
{
TilemapCamera.orthographicSize = 20;
}
}
}
/// <summary>
/// 获取点击的Tilemap坐标
/// </summary>
/// <param name="camera"></param>
/// <param name="tilemap"></param>
/// <returns></returns>
public Vector3Int GetGridPos(Camera TilemapCamera,Tilemap tilemap)
{
// 屏幕坐标 转 世界坐标
Vector3 wordPos = TilemapCamera.ScreenToWorldPoint(Input.mousePosition);
//Debug.LogError(wordPos);
// 世界坐标 转 格子坐标
Vector3Int callPos = tilemap.WorldToCell(wordPos);
return callPos;
}
}