这里以左右拖拽为例子
要先调用 SetMoveRange 设置拖拽bg
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CameraMove : MonoBehaviour
{
public float CAM_Xspeed = 1;//速度
public EventSystem es;
Graphics a;
// 背景图片的宽度
private float bgWidth;
private bool isDrag = false;
Vector3 inputPos = Vector3.zero;
public void SetMoveRange(SpriteRenderer bg)
{
// 获取当前拖拽场景背景图片宽度
bgWidth = bg.sprite.bounds.size.x * bg.transform.localScale.x;
}
//ui阻挡射线检测
bool CheckGuiRaycastObjects()
{
PointerEventData eventData = new PointerEventData(es);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
changePanel.GetComponent<GraphicRaycaster>().Raycast(eventData, list);
return list.Count > 0;
}
private Vector3 dragStarPos = Vector3.zero;
private void Update()
{
//摄像机拖动
if (!EventSystem.current.IsPointerOverGameObject())
{
if (CheckGuiRaycastObjects())
{
return;
}
if (Input.GetMouseButtonDown(0))//判断鼠标是否按下
{
inputPos = Input.mousePosition;
RaycastHit outHit;
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out outHit);
if (outHit.collider != null)
{
isDrag = true;
dragStarPos = inputPos;
}
}
if (Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
isDrag = false;
inputPos = Input.mousePosition;
RaycastHit outHit;
bool hit = Physics.Raycast(ray, out outHit);
if (outHit.collider != null)
{
if (Vector3.Distance(dragStarPos, inputPos)>1)
{
return;
}
//在这里处理射线检测点击事件
if (outHit.collider.tag == Tags.Creat)
{
}
else if (outHit.collider.tag == Tags.Relax)
{
}
}
}
}
}
private void FixedUpdate()
{
if (isDrag)
{
// 摄像机的一半宽度
float hight = Camera.main.orthographicSize;
// 摄像机的一半高度,会随分辨率的宽高比成正比
// 用高度乘以分辨率的宽高比得到宽度
float width = hight * Screen.width / Screen.height;
// 要移动到的位置
Vector3 temp = new Vector3(transform.position.x + Input.GetAxis("Mouse X") * -CAM_Xspeed * Time.fixedDeltaTime, transform.position.y, transform.position.z);
// 当角色的横坐标 + 摄像机的一半宽度大于背景图片的一半宽度,则为到了边界,把摄像机的宽度设为临界点
if (width + Mathf.Abs(temp.x) > bgWidth / 2)
{
temp = new Vector3(Mathf.Sign(temp.x) * (bgWidth / 2 - width), transform.position.y, transform.position.z);
}
else
{
// 否则则为正常移动
temp = new Vector3(temp.x, transform.position.y, transform.position.z);
}
// 实现摄像机的延迟移动
transform.position = temp;
}
}
}