牛骨文教育服务平台(让学习变的简单)
博文笔记

unity3D获取屏幕宽高

创建时间:2017-10-14 投稿人: 浏览次数:770

这里要用到一个摄像机函数Camera.ViewportToWorldPoint, Unity官方对其定义为: 
Camera.ViewportToWorldPoint 视窗转世界位置 
function ViewportToWorldPoint (position : Vector3) : Vector3

Description描述

Transforms position from viewport space into world space.

从视窗空间到世界空间的变换位置。

Viewport space is normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). The z position is in world units from the camera.

视口空间是归一化的并相对于相机的,相机的左下为(0,0);右上是(1,1);Z的位置是以世界单位衡量的到相机的距离。

Note that it transforms a x-y screen position, into a x-y-z position in 3D space.

请注意它是变换一个x-y屏幕位置到一个3D空间的x-y-z位置。

You provide the function with a vector where the x-y components of the vector are the screen coordinates and the z component is the distance of the resulting plane from the camera.

这个函数带有在屏幕坐标的x-y组件向量,并且z组件是在从相机产生的平面的距离。

看了官方文档,现在我们知道怎么获取屏幕的实际宽高,下面是示例代码:

    private float width;
    private float height;

    void SetBasicValues(){

        float leftBorder;
        float rightBorder;
        float topBorder;
        float downBorder;
        //the up right corner
        Vector3 cornerPos=Camera.main.ViewportToWorldPoint(new Vector3(1f,1f,Mathf.Abs(Camera.main.transform.position.z)));

        leftBorder=Camera.main.transform.position.x-(cornerPos.x-Camera.main.transform.position.x);
        rightBorder=cornerPos.x;
        topBorder=cornerPos.y;
        downBorder=Camera.main.transform.position.y-(cornerPos.y-Camera.main.transform.position.y);

        width=rightBorder-leftBorder;
        height=topBorder-downBorder;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

得到的width与height就是屏幕宽高,代码的含义上面已经说的很清楚了。

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。