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

Unity Windows构建下如何实现屏幕横竖屏切换?

Unity Windows构建实现屏幕旋转方案

方案一:系统级屏幕旋转(适合全屏独占场景)

Windows平台下Screen.orientation确实仅对移动设备生效,若要实现类似移动端的全局旋转效果,可调用Windows系统API修改显示器方向——但注意这会影响整个屏幕,而非仅游戏窗口:

using System.Runtime.InteropServices;

public class SystemScreenRotation
{
    [DllImport("user32.dll")]
    private static extern bool SetDisplayConfig(uint numPathArrayElements, IntPtr pathArray, uint numModeArrayElements, IntPtr modeArray, uint flags);

    private const uint SDC_APPLY = 0x00000080;
    private const uint SDC_ROTATE_90 = 0x00000001;
    private const uint SDC_ROTATE_180 = 0x00000002;
    private const uint SDC_ROTATE_270 = 0x00000003;

    public static void RotateTo(ScreenOrientation targetOrientation)
    {
        uint rotateFlag = targetOrientation switch
        {
            ScreenOrientation.LandscapeRight => SDC_ROTATE_90,
            ScreenOrientation.LandscapeLeft => SDC_ROTATE_270,
            ScreenOrientation.PortraitUpsideDown => SDC_ROTATE_180,
            _ => 0 // 默认竖屏
        };
        SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SDC_APPLY | rotateFlag);
    }
}
  • 注意:该方法需要游戏以管理员权限运行,否则可能调用失败;仅推荐全屏独占游戏使用,窗口模式下会导致整个系统屏幕旋转,体验不佳。

方案二:游戏内容内部旋转(推荐,仅影响游戏)

如果只想让游戏内的画面和UI旋转,不干扰系统屏幕,可通过调整相机、UI和输入适配实现:

1. 相机旋转与分辨率适配

给主相机挂载脚本,调整旋转角度同时修正宽高比:

public class GameCameraRotator : MonoBehaviour
{
    public void RotateCamera(ScreenOrientation targetOrientation)
    {
        Quaternion newRotation = targetOrientation switch
        {
            ScreenOrientation.LandscapeLeft => Quaternion.Euler(0, 0, 90),
            ScreenOrientation.LandscapeRight => Quaternion.Euler(0, 0, -90),
            ScreenOrientation.PortraitUpsideDown => Quaternion.Euler(0, 0, 180),
            _ => Quaternion.Euler(0, 0, 0)
        };
        Camera.main.transform.rotation = newRotation;

        // 适配旋转后的宽高比,避免画面拉伸
        float newAspect = (float)Screen.height / Screen.width;
        Camera.main.aspect = newAspect;
    }
}

2. UI适配

针对UGUI做如下调整:

  • 将Canvas的Render Mode设为Screen Space - Camera,绑定主相机
  • 在Canvas Scaler组件中选择Scale With Screen Size,设置Reference Resolution为目标分辨率(比如竖屏用1080x1920)
  • 直接旋转Canvas的父物体(或Canvas自身),旋转角度与相机保持一致,所有子UI元素会自动继承旋转属性

3. 输入坐标转换

旋转后鼠标、触摸输入的坐标会错位,需做坐标转换,以90度顺时针旋转为例:

public Vector2 GetAdjustedInputPos(Vector2 rawScreenPos)
{
    // 根据实际旋转角度调整转换逻辑
    float adjustedX = Screen.height - rawScreenPos.y;
    float adjustedY = rawScreenPos.x;
    return new Vector2(adjustedX, adjustedY);
}

补充注意事项

  • 3D游戏需额外调整物理参数(比如重力方向),避免旋转后物理行为异常
  • 测试时覆盖不同分辨率场景,确保UI和游戏元素无拉伸、错位问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:22:25