- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Test01 : MonoBehaviour
- {
- Transform cam;//相机物体
- Vector3 pos;
- // Start is called before the first frame update
- void Start()
- {
- pos = transform.position;
- cam = GameObject.FindWithTag("MainCamera").transform;
- }
- // Update is called once per frame
- void Update()
- {
- Vector3 offset = pos - cam.position;//相对相机的偏移位置
- Vector3 camSize = new Vector3(1.51f*(1920f/1080f)-0.2f, 1.51f-0.2f,0);//相机的宽度和高度的一半尺寸,这里假设相机的高度一半为1.51
- camSize = camSize - new Vector3(0.2f, 0.2f, 0);//在坐标在屏幕外时,让自己在屏幕内离边缘一段距离0.2
- //判断是在屏幕内还是屏幕外
- bool isInCam = (Mathf.Abs(offset.x) < camSize.x) && (Mathf.Abs(offset.y) < camSize.y);
- //如果是在屏幕内,那么坐标位置等于自己的坐标位置
- //如果是在屏幕外,那么坐标位置在屏幕边缘
- if (isInCam) {
- transform.position = pos;
- }
- else {
- float x=pos.x;
- if (Mathf.Abs(offset.x) > camSize.x) x = Mathf.Sign(offset.x) * camSize.x + cam.position.x;
- //x = x + -Mathf.Sign(offset.x) * 0.2f;
-
- float y = pos.y;
- if (Mathf.Abs(offset.y) > camSize.y) y = Mathf.Sign(offset.y) * camSize.y + cam.position.y;
- //y = y + -Mathf.Sign(offset.y) * 0.2f;
- transform.position =new Vector3(x, y, 0);
- }
- }
- //判断是在屏幕内还是屏幕外
- //如果是在屏幕内,那么坐标位置等于自己的坐标位置
- //如果是在屏幕外,那么坐标位置在屏幕边缘
-
- private void OnDrawGizmos()
- {
- //Gizmos.color = Color.red;
- //float x = 1920f / 1080f;
- //Gizmos.DrawCube(transform.position, new Vector3(1.51f * (1920f / 1080f), 1.51f, 0) * 2);
- }
- }