Files
5.24BuYu/Assets/ScreenBorderToWorld.cs
T
2026-05-08 06:49:53 +08:00

63 lines
1.7 KiB
C#

using UnityEngine;
public class ScreenBorderToWorld : MonoBehaviour
{
[Header("四个空对象(顺序:上、下、左、右)")]
public Transform topPoint;
public Transform bottomPoint;
public Transform leftPoint;
public Transform rightPoint;
[Header("四个特效(顺序:上、下、左、右)")]
public GameObject topFX;
public GameObject bottomFX;
public GameObject leftFX;
public GameObject rightFX;
[Header("目标相机(不填默认主相机)")]
public Camera cam;
private void Start()
{
if (cam == null) cam = Camera.main;
// 上
SetPos(topPoint, topFX, new Vector2(0.5f, 1f));
// 下
SetPos(bottomPoint, bottomFX, new Vector2(0.5f, 0f));
// 左
SetPos(leftPoint, leftFX, new Vector2(0f, 0.5f));
// 右
SetPos(rightPoint, rightFX, new Vector2(1f, 0.5f));
}
/// <summary>
/// 归一化屏幕坐标 → 世界坐标 → 设置空对象与特效
/// </summary>
private void SetPos(Transform point, GameObject fx, Vector2 normalizedPos)
{
// 1. 归一化坐标 → 屏幕像素坐标
float px = normalizedPos.x * Screen.width;
float py = normalizedPos.y * Screen.height;
Vector3 screenPos = new Vector3(px, py, 0);
// 2. 使用你已有的转换类
Vector3 worldPos = CoordinateTransformation.ScreenToWord(screenPos);
// 3. 设置空对象位置
if (point != null)
point.position = worldPos;
// 4. 设置特效位置
if (fx != null)
fx.transform.position = worldPos;
Vector3 v3 = fx.transform.transform.position;
v3.z = 0;
fx.transform.position = v3;
}
}