You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何锁定游戏对象位置,不受分辨率影响?

解决Unity FPS枪械锁定屏幕右下角不受分辨率影响的问题

方法1:用UI系统挂载枪械(最简便的适配方案)

  • 创建Canvas,将Render Mode设为Screen Space - Overlay(无需绑定相机)或Screen Space - Camera(若需和3D场景交互,绑定主相机)
  • 给枪械模型添加带RectTransform的父对象,将这个父对象放到Canvas下
  • 选中父对象的RectTransform,设置**锚点(Anchor)**为(1, 0),**轴心(Pivot)**也设为(1, 0),调整Offset的X、Y值,把枪械固定在右下角的合适位置
  • 这种方式下,UI元素会自动适配任何分辨率,枪械位置不会偏移

方法2:脚本计算视口位置(保留3D层级)

如果要维持枪械作为相机子对象的3D属性,用脚本基于视口坐标动态更新位置:

  • 给枪械挂载以下C#脚本:
using UnityEngine;

public class LockGunToCorner : MonoBehaviour
{
    [SerializeField] private Camera mainCamera;
    [SerializeField] private Vector2 cornerOffset = new Vector2(0.1f, 0.1f); // 右下角偏移量,范围0~1
    private float fixedZDistance;

    void Awake()
    {
        if (mainCamera == null) mainCamera = Camera.main;
        fixedZDistance = transform.localPosition.z; // 记录初始Z轴距离,避免远近变化
    }

    void Update()
    {
        // 视口坐标:(0,0)=左下角,(1,1)=右上角,计算带偏移的右下角视口位置
        Vector3 viewportPos = new Vector3(1 - cornerOffset.x, cornerOffset.y, fixedZDistance);
        // 转换为世界坐标并更新枪械位置
        transform.position = mainCamera.ViewportToWorldPoint(viewportPos);
    }
}
  • 注意:fixedZDistance要设为相机前方的固定值(比如0.8米),避免分辨率变化时枪械大小异常

方法3:强制相机保持固定宽高比(适配黑边方案)

如果是相机投影拉伸导致的位置偏移,给主相机挂载脚本强制锁定宽高比:

using UnityEngine;

public class LockCameraAspect : MonoBehaviour
{
    [SerializeField] private float targetAspect = 16f / 9f; // 目标宽高比

    void Start() => AdjustCamera();

    void Update()
    {
        if (Mathf.Abs(Screen.width / (float)Screen.height - targetAspect) > 0.01f)
            AdjustCamera();
    }

    void AdjustCamera()
    {
        Camera cam = GetComponent<Camera>();
        float windowAspect = Screen.width / (float)Screen.height;
        float scale = windowAspect / targetAspect;

        Rect rect = cam.rect;
        if (scale < 1f)
        {
            rect.height = scale;
            rect.y = (1f - scale) / 2f;
            rect.width = 1f;
            rect.x = 0f;
        }
        else
        {
            scale = 1f / scale;
            rect.width = scale;
            rect.x = (1f - scale) / 2f;
            rect.height = 1f;
            rect.y = 0f;
        }
        cam.rect = rect;
    }
}
  • 这种方法会让相机在分辨率变化时保持目标宽高比,用黑边填充多余区域,枪械作为相机子对象的相对位置不会改变

内容的提问来源于stack exchange,提问作者Dakota

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:15:27